我在运行多线程应用程序时遇到问题。让我解释。我有一个for循环,它创建了n个线程,这些n个线程再次为它们创建了两个2个线程。 所以最后我有2 * n个线程必须在同一时间运行。
我可以在我的程序中看到创建了几个线程,但是在创建了n个线程之后,只有第一对线程正在工作。最后n-1个其他几个线程什么都不做。
以下是我的代码:
void *thread1_send (void * arg_threads)
{
// do some work
pthread_exit (0);
}
void *thread2_listen (void * arg_threads)
{
// do some work
pthread_exit (0);
}
void *thread_multi (void * arg_threads)
{
// first thread
if (pthread_create (&th1, NULL, thread1_send, arg_threads) < 0) {
printf ("Error pthread_create for thread 1\n");
exit (1);
}
//second thread
if (pthread_create (&th2, NULL, thread2_listen, arg_threads) < 0) {
printf ("Error pthread_create for thread 2\n");
exit (1);
}
(void)pthread_join (th1, &ret_t);
(void)pthread_join (th2, &ret_t);
pthread_exit(0);
}
pthread_t * th_multi = (pthread_t *) malloc( n * sizeof(*th_multi) );
....
....
// for loop in a function
for(int i=0; i<n; i++)
{
// creation of n threads
if (pthread_create (&th_multi[i], NULL, thread_multi, arg_threads) < 0) {
printf ("Error pthread_create for thread_multi [%d].\n", i);
exit (1);
}
pthread_exit(0); // it's unclear for me what pthread_exit is doing here.
} // end of for