How to create n threads?

I am trying to write a multi-threaded program, the number of threads based on the input on the command line, and therefore I can not hard-code the previously declared threads. Is this the right way to do this?

int threads = 5; // (dynamic, not hard-coded) int i = 0; pthread_t * thread = malloc(sizeof(pthread_t)*threads); for (i = 0; i < threads; i++) { pthread_t foobar; thread[i] = foobar; // will this cause a conflict? } for (i = 0; i < threads; i++) { int ret = pthread_create(&thread[i], NULL, (void *)&foobar_function, NULL); if(ret != 0) { printf ("Create pthread error!\n"); exit (1); } } 

Here is my result from the changes suggested below. Everything seems to be working fine.

 int threads = 5; int i; pthread_t * thread = malloc(sizeof(pthread_t)*threads); for (i = 0; i < threads; i++) { int ret = pthread_create(&thread[i], NULL, &foobar_function, NULL); if(ret != 0) { printf ("Create pthread error!\n"); exit (1); } // pthread_join(thread[i], NULL); // don't actually want this here :) } sleep(1); // main() will probably finish before your threads do, free(thread); // so we'll sleep for illustrative purposes 
+8
c pthreads
source share
3 answers

What is in the first cycle? Do array elements set an uninitialized value?

So, I think you need:

 int threads = 5, i = 0, ret = -1; pthread_t * thread = malloc(sizeof(pthread_t)*threads); for (i = 0; i < threads; i++) { ret = pthread_create(&thread[i], NULL, &foobar_function, NULL); if(ret != 0) { printf ("Create pthread error!\n"); exit (1); } } 

It spawns streams of threads , starting with foobar_function in each. And you have (if everything goes well :)) their identifiers in the thread array. So, for example, you can cancel the second thread by calling pthread_cancel(thread[1]) , etc.

+7
source share

The first for loop is not valid C, and I'm not sure what you want. Just delete it, and the rest of the code looks fine, except for clicking the foobar_function . Cast should be:

 (void *(*)(void *))foobar_function 

but if the type is already there or something is very close, your program probably has undefined behavior. It would be better to fix the function signature so that there is no need for casting.

+1
source share

If you are trying to write a multi-threaded program, but do not understand how to distribute a dynamic data structure, you may be mistaken.

Learn to walk before you run.

Consider using a simpler language and avoid using (explicit) threads.

Threads are very difficult to use correctly; dynamic-size arrays are very easy to reach (even pretty easy in C)

-2
source share

All Articles