Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating multiple threads in C

I am just a beginner in Programming using C.For my college project I want to create a multi-threaded server application to which multiple clients can connect and transfer there data which can be saved in a database.

After going through many tutorials I got confused about how to create multiple threads using pthread_create.

Somewhere it was done like:

pthread_t thr;

pthread_create( &thr, NULL ,  connection_handler , (void*)&conn_desc);

and somewhere it was like

 pthread_t thr[10];

 pthread_create( thr[i++], NULL ,  connection_handler , (void*)&conn_desc);

I tried by implementing both in my application and seems to be working fine. Which approach of the above two is correct which I should follow. sorry for bad english and description.

like image 942
Ramanujam Avatar asked Jan 28 '16 12:01

Ramanujam


2 Answers

Both are equivalent. There's no "right" or "wrong" approach here.

Typically, you would see the latter when creating multiple threads, so an array of thread identifiers (pthread_t) are used.

In your code snippets, both create just a single thread. So if you want to create only one thread, you don't need an array. But this is just like declaring any variable(s) that you didn't use. It's harmless.

In fact, if you don't need the thread ID for any purpose, (for joining or changing attributes etc.), you can create multiple threads using a single thread_t variable without using an 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 just fine. Note that the cast to void* is unnecessary (last argument to pthread_create()). Any data pointer can be implicitly converted to void *.

like image 186
P.P Avatar answered Nov 09 '22 06:11

P.P


Sample Example of multiple thread :

#include<iostream>    
#include<cstdlib>    
#include<pthread.h>

using namespace std;

#define NUM_THREADS 5

struct thread_data
{
  int  thread_id;
  char *message;
};


void *PrintHello(void *threadarg)
{
   struct thread_data *my_data;   

   my_data = (struct thread_data *) threadarg;

   cout << "Thread ID : " << my_data->thread_id ;

   cout << " Message : " << my_data->message << endl;

   pthread_exit(NULL);
}

int main ()
{
   pthread_t threads[NUM_THREADS];

   struct thread_data td[NUM_THREADS];

   int rc, i;


   for( i=0; i < NUM_THREADS; i++ )    
   {

      cout <<"main() : creating thread, " << i << endl;

      td[i].thread_id = i;

      td[i].message = "This is message";

      rc = pthread_create(&threads[i], NULL,

                          PrintHello, (void *)&td[i]);

      if (rc){

         cout << "Error:unable to create thread," << rc << endl;

         exit(-1);    
      }    
   }    
   pthread_exit(NULL);    
}
like image 32
msc Avatar answered Nov 09 '22 07:11

msc