pthread_join的作用


使用 pthread_create 創建線程后主進程結束,創建的線程也會結束,使用 pthread_join 可以阻塞主線程。

#include <pthread.h>
#include <stdio.h>
#include <Windows.h>
#pragma comment(lib, "pthreadVC2.lib")

static int count = 0;

void* thread_run(void* parm)
{
    for (int i=0;i<5;i++)
    {
        count++;
        printf("The thread_run method count is = %d\n",count);
        Sleep(1000);
    }
    return NULL;
}

int main()
{
    pthread_t tid;
    pthread_create(&tid, NULL, thread_run,NULL);
    // 加入pthread_join后,主線程"main"會一直等待直到tid這個線程執行完畢自己才結束
    // 一般項目中需要子線程計算后的值就需要加join方法
    pthread_join(tid,NULL);
    // 如果沒有join方法可以看看打印的順序
    printf("The count is = %d\n",count);
    getchar();//用於阻塞主線程
    return 0;
}

如果不阻塞,創建的線程無法正常執行


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM