multithreading - Creating multiple threads in C -
i beginner in programming using c.for college project want create multi-threaded server application multiple clients can connect , transfer there data can saved in database.
after going through many tutorials got confused how create multiple threads using pthread_create.
somewhere done like:
pthread_t thr; pthread_create( &thr, null , connection_handler , (void*)&conn_desc);
and somewhere like
pthread_t thr[10]; pthread_create( thr[i++], null , connection_handler , (void*)&conn_desc);
i tried implementing both in application , seems working fine. approach of above 2 correct should follow. sorry bad english , description.
both equivalent. there's no "right" or "wrong" approach here.
typically, see later when creating multiple threads, array of thread identifiers (pthread_t
) used.
in code snippets, both create single thread. if want create 1 thread, don't need array. declaring variable(s) didn't use. it's harmless.
in fact, if don't need thread id purpose, (for joining or changing attributes etc), can create multiple threads using single thread_t
variable without using array.
the following
pthread_t thr; size_t i; for(i=0;i<10;i++) { pthread_create( &thr, null , connection_handler , &conn_desc); }
would work fine. note cast void*
unnecessary (last argument pthread_create()
). data pointer can implicitly converted void *
.
Comments
Post a Comment