Creating multiple threads in C

I'm just starting to program using C. For my college project, I want to create a multi-threaded server application to which several clients can connect and transfer there data that can be stored in a database.

After going through many lessons, I was confused about how to create multiple threads using pthread_create.

Somewhere this was done as:

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 to implement both in my application and it seems to work fine. Which approach of these two rules is correct, and I must follow. Sorry for the poor english and description.

+4
source share
3 answers

. "" "" .

, , (pthread_t).

. , , . , (-), . .

, - ( ..), , thread_t .

pthread_t thr;
size_t i;

for(i=0;i<10;i++) {
   pthread_create( &thr, NULL , connection_handler , &conn_desc);
}

. , void* ( pthread_create()). void *.

+2

, , .

( ) 10 .

pthread_t , , 10 , 10 .

0

An example of an example of several threads:

#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);    
}
0
source

Source: https://habr.com/ru/post/1626351/


All Articles