簡體   English   中英

如何使一個pthread發出另一個可以繼續執行的信號?

[英]How to make a pthread signal another that it can continue executing?

我有三個整數(a,b和c),我想創建兩個線程( POSIX pthreads )以此特定順序訪問它們,以保持結果一致:

Thread 1  |  Thread 2
---------------------
a=1          b=5
c=7
             c=c+10
             b=a+c*2
a=b+b*10

也就是說,線程2中的c = c + 10必須等待,直到線程1中的c = 7完成。 另外,線程1中的a = b + b * 10必須等待,直到線程2中的b = a + c * 2完成。

我已經嘗試過使用互斥鎖,但是它不能按我的預期工作(下面的代碼)。 如果先啟動線程2,則可以在線程1鎖定互斥鎖之前鎖定互斥鎖1,因此序列丟失。 從主線程鎖定互斥鎖不是一種選擇,因為它將產生未定義的行為(互斥鎖被鎖定,然后由另一個線程解鎖)。 我也嘗試過使用條件變量,但是會出現類似的問題:在關聯的等待之前可能會發生信號。

#include <pthread.h>
#include <stdio.h>

int a, b, c;
pthread_mutex_t mutex1, mutex2 = PTHREAD_MUTEX_INITIALIZER;

void *thread1(void *arg) {
    pthread_mutex_lock(&mutex1);
    a = 1;
    c = 7; 
    pthread_mutex_unlock(&mutex1);
    pthread_mutex_lock(&mutex2);
    a = b + b*10; 
    pthread_exit(NULL);
}

void *thread2(void *arg) {
    pthread_mutex_lock(&mutex2);
    b = 5;
    pthread_mutex_lock(&mutex1);
    c = c + 10;
    b = a + c*2;
    pthread_mutex_unlock(&mutex2);
    pthread_exit(NULL);
}

int main() {
    pthread_t t1, t2;

    if(pthread_create(&t1, NULL, thread1, NULL)) {
        fprintf(stderr, "Error creating Thread 1\n");
        return 0;
    }
    if(pthread_create(&t2, NULL, thread2, NULL)) {
        fprintf(stderr, "Error creating Thread 2\n");
        return 0;
    }

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);

    return a;
}

我的問題是,使用pthreads實現線程排序的正確方法是什么? 提前致謝。

pthread_mutex_t mutex1, mutex2 = PTHREAD_MUTEX_INITIALIZER

僅初始化第二個; 但這是一種選擇。 取決於您正在運行的系統,您可能不會注意到這一點,因為Mutex1未初始化,因此對其進行的操作可能會失敗,或者初始化程序常量可能為零。

信號/等待問題不是問題-您以這種模式等待由互斥鎖保護的條件:

lock();
while (check() == false) {
    wait();
}
func();
signal();
unlock();

因此thread1的檢查為true,func為c = 7,而thread2的檢查為(c == 7),func為c + = 10

暫無
暫無

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

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