簡體   English   中英

pthread_join 和 pthread 奇怪的行為

[英]pthread_join and pthread weird behaviour

我有 2 個進程,每個進程通過下面的代碼創建多個線程(在本例中為 2 個)。 當我將 pthread_join 放在 create 正下方時,它可以工作,但它總是按順序調用線程。 我想在不同的循環中進行連接,如下所示。 問題是當我出於某種原因這樣做時,它會創建雙倍的相同線程而不是 2 個不同的線程。

因此,當線程運行時,它會打印類似“線程 2.2 已啟動,線程 2.2 已啟動,線程 1.2 已啟動,線程 1.2 已啟動”,其中第一個數字是進程號,第二個是線程號。它們應該是“1.2 1.1 2.1 2.2”。 有人可以幫忙嗎?

for(int i = 0; i<num_of_t;i++){
        struct threadst args;
        args.globalcp = globalcp;
        args.lock = lock;
        args.num1 = num1+i*((num2-num1+1)/num_of_t);
        args.num2 = args.num1+((num2-num1+1)/num_of_t)-1;
        args.threadid =i;
        args.pid = myOrder;
        pthread_create(&threads[i], &attr, findPrimes, (void *)&args);
        pthread_join(threads[i], &status);
    }

    //for(int i = 0; i<num_of_t;i++){
        //pthread_join(threads[i], &status);
    //}

首先,您在每個線程創建( &args )時傳遞相同的 object,因此它在所有線程之間共享。 因此,根據需要給每個它自己的。

其次,不要在線程創建后立即調用pthread_join ,否則會重新引入順序性(join 是等待線程結束的阻塞操作)。 通常你需要啟動你的線程,然后在稍后的某個時間點調用你需要等待的線程上的 join。

// create an array of args to be passed each for a given thread
struct threadst *args = malloc(sizeof(struct threadst)*num_of_t;
// need a test for malloc...

for(int i = 0; i<num_of_t;i++){
    struct threadst *arg = args+i;
    arg->globalcp = globalcp;
    arg->lock     = lock;
    arg->num1     = num1+i*((num2-num1+1)/num_of_t);
    arg->num2     = arg->num1+((num2-num1+1)/num_of_t)-1;
    arg->threadid = i;
    arg->pid      = myOrder;
    pthread_create(&threads[i], &attr, findPrimes, (void *)arg);
}

// do something else in the meantime

for (int i = 0; i<num_of_t;i++) {
    pthread_join(threads[i], &status);
}

暫無
暫無

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

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