我想了解多线程如何工作。我已经写了下面的代码 `并发多线程
void handler(void *arg)
{
printf("Printf from cleanup handler: %s\n", (char*)arg);
}
void print(const char *msg)
{
printf("%7s: Pid=%d Tid:%lu\n", msg, getpid(), pthread_self());
}
void* thread_function1(void *args)
{
printf("Received: %d\n", (int)args);
print("Thread");
pthread_cleanup_push(handler, "hello");
pthread_cleanup_pop(1);
printf("Thread Done\n");
return (void *) 0;
}
int main(void)
{
pthread_t tid1, tid2;
void *tret;
if(pthread_create(&tid1, NULL, thread_function1, (void *)1))
exit(1);
if(pthread_create(&tid2, NULL, thread_function1, (void *)2))
exit(1);
// pthread_join(tid2, &tret);
// pthread_join(tid1, &tret);
}
这段代码的问题是,主要完成其执行之前thread_function1
能够完成它的执行。如果两个注释都被删除,那么thread 2
仅在thread 1
已经完成其执行后才被执行。
我想要做的是有thread 1
和thread 2
同时执行和main
应该等待两个线程完成。
线程做了一个(非平凡的)工作量吗?难道是'thread_function1'在第二个线程被创建之前完成? –
@WanderNauta我已经更新了这个问题。请看看它。 – Ibrahim