[英]pthread creation not working properly
i have this piece of code:我有这段代码:
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <time.h>
int number;
pthread_mutex_t *mutex;
pthread_t *threads;
void *PrintHello(void *threadid)
{
long tid;
tid = (long)threadid;
printf("Hello World! It's me, thread #%ld!\n", tid);
time_t rawtime;
struct tm * time_start;
time ( &rawtime );
time_start = localtime ( &rawtime );
printf ( "The number %ld thread is created at time %s \n",tid, asctime (time_start));
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
int i,rc;
printf("give threads");
scanf("%d",&number);
mutex = calloc( number, sizeof(*mutex));
threads = calloc(number, sizeof(*threads));
for (i = 0; i < number;i++) {
pthread_mutex_init( &mutex[i],NULL);
}
for(i=0; i<number; i++){
printf("In main: creating thread %d\n", i);
rc = pthread_create(&threads[i], NULL, PrintHello, (void *)i);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
return 0;
}
The purpose of this code is to ask the user to give the number of the threads that it is going to create and after the creation of the threads,the thread itself will print 2 messages saying the number of the thread and the time that it was created.这段代码的目的是要求用户提供将要创建的线程数,在创建线程后,线程本身将打印 2 条消息,说明线程数和创建时间创建。
The problem is that inside the main the message "In main: creating thread"
is showing up but the message inside the threads sometimes does not.问题是在主内部显示消息
"In main: creating thread"
,但线程内部的消息有时没有。
For example, it would create 3 threads and only 1 thread will show up its message and that thread also will not show up the time that was created.例如,它将创建 3 个线程,只有 1 个线程会显示其消息,并且该线程也不会显示创建的时间。 I dont know if there is something wrong with the code.
不知道是不是代码有问题。
Root Cause:根本原因:
Your main()
exits before the child threads get an opportunity to complete their task.您的
main()
在子线程有机会完成其任务之前退出。
Solution:解决方案:
You need to make sure that the main()
waits until all the threads have completed their work.您需要确保
main()
等待所有线程完成其工作。
You need to use:您需要使用:
to achieve this functionality.来实现这个功能。 Add the following before returning from
main()
:在从
main()
返回之前添加以下内容:
for(i=0; i<number; i++)
{
pthread_join(threads[i], NULL);
}
Other problems:其他问题:
Return from main()
is equivalent to calling exit(...)
, which terminates the whole process.从
main()
返回相当于调用exit(...)
,它终止了整个过程。 You may use pthread_join()
to wait for each non-main thread, like another answer advises, or you may call pthread_exit(NULL)
in the end of your main()
: it would exit the initial thread, but other threads will continue to run.您可以使用
pthread_join()
来等待每个非主线程,就像另一个答案所建议的那样,或者您可以在main()
的末尾调用pthread_exit(NULL)
main()
:它会退出初始线程,但其他线程将继续跑步。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.