我想了解多線程如何工作。我已經寫了下面的代碼 `併發多線程
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