Creating multiple threads in C
Asked Answered
R

4

10

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.

Rape answered 28/1, 2016 at 12:43 Comment(5)
Both of them are using the same method pthread_create, so in a sense they are doing the same thing. Other than that, it is a matter of choice how to store the pthread handle (of type pthread_t). The second one seems to be storing at most ten threads, and the first one is just dealing with a single thread.Manriquez
The second one with thr[i++] should be &thr[i++].Hydroquinone
@Selçuk Cihan If i do something like for(i=0;i<10;i++) pthread_create( &thr, NULL , connection_handler , &conn_desc); Then will it also create 10 threads ?Rape
Yes it will create ten threads but you will lose the reference for the first nine of them.Manriquez
Possible duplicate of How do I start threads in plain C?Mcginn
D
4

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 *.

Discommon answered 28/1, 2016 at 12:49 Comment(3)
@I3x if I need to create 100 threads then i need to follow the second approach with pthread_t thr[100] or will the first approach also solve my problem .Rape
Even if you want to create 100 threads, you are not still required to use an array (pthread_t thr[100]). You only need to store IDs if you want to do something with them later. So it depends on your application. See the update.Discommon
@Rape - It will be easier to use pthread_t thr[100], especially if you want all 100 threads to do the same thing. Otherwise, you'd need 100 variables to keep track of the pthread_t handles.Hydroquinone
I
3

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);    
}
Infringement answered 28/1, 2016 at 12:53 Comment(1)
How to confirm each thread process completed? Do we need to use "pthread_join" function? The other question is why "pthread_exit" at the "main" function? Is this for waiting each thread ending?Yoshikoyoshio
N
0

The first one you provided creates a single thread.

The second one (if looped) has the potential to spawn 10 threads.

Basically the pthread_t type is a handler for the thread so if you have an array of 10 of them then you can have 10 threads.

Nomenclature answered 28/1, 2016 at 12:49 Comment(0)
V
0

For everyone, use a thread list because it will not be free if you call once pthread_join().

Code exemple :

int run_threads(void)
{
    int listLength = 5;
    pthread_t thread[listLength];

    //Create your threads(allocation).
    for (int i = 0; i != listLength; i++) {
        if (pthread_create(&thread[i], NULL, &routine_function, NULL) != 0) {
            printf("ERROR : pthread create failed.\n");
            return (0);
        }
    }
    //Call pthread_join() for all threads (they will get free) and all threads 
    //will terminate at this position.
    for (int i = 0; i != listLength; i++) {
        if (pthread_join(thread[i], NULL) != 0) {
            printf("ERROR : pthread join failed.\n");
            return (0);
        }
    }
    //return 1 when all threads are terminated.
    return (1);
}
Vanhoose answered 18/4, 2022 at 16:43 Comment(1)
I see the user msc snippet didn't have "pthread_join". What are advantage and disadvantage of the your approach?Yoshikoyoshio

© 2022 - 2024 — McMap. All rights reserved.