簡體   English   中英

計算線程運行多少次?

[英]count how many times the threads running?

例如,使用pthread_create創建兩個線程,它們兩個都打印“ hello world”,我的問題是如何計算每個線程打印“ hello world”多少次?

我的問題是如何計算每個線程打印多少次“ hello world”?

最簡單的方法是在文件頂部聲明一個全局原子計數器:

static std::atomic<int> counter = 0;

然后讓每個線程在每次打印“ hello world”時都增加計數器(即++ counter)。 然后,在main()中,在所有線程都加入后,您可以打印出值計數器。

我可以向您展示子線程將變量傳遞給主線程的代碼;

void * thread_func(void *arg)
{
    int num = 10; //assume 'num' is the times that child thread  printed "hello world"
    pthread_exit((void *)num);
}

int main()
{
    pthread_t thread;
    void * tret;
    pthread_create(&thread,NULL,thread_func,NULL);
    pthread_join(thread,&tret);
    printf("%d\n",(int)tret);  
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM