我有三個整數(A,B和C),我想創建兩個線程(POSIX 的pthreads)來訪問他們在這個特定的順序,以保持結果一致:如何製作一個可以繼續執行的pthread信號?
Thread 1 | Thread 2
---------------------
a=1 b=5
c=7
c=c+10
b=a+c*2
a=b+b*10
那是,thread2中的c = c + 10必須等到thread1中的c = 7完成。此外,thread1中的a = b + b * 10必須等到thread2中的b = a + c * 2完成。
我一直在使用互斥試過,但我打算(下面的代碼)這是行不通的。如果thread2首先啓動,它可以在thread1鎖定它之前鎖定mutex1,因此排序會丟失。鎖定主線程中的互斥鎖不是一種選擇,因爲它會產生未定義的行爲(互斥鎖被另一個線程鎖定然後解鎖)。我也試過使用條件變量,但也出現了類似的問題:信號可能發生在關聯的等待之前。
#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?提前致謝。
不應這些'的INT A,b,C;'變量是易失性? – Gaurav
@usr我在這裏簡單的代碼,真正的代碼有並行 –
執行看也不看深度更大的塊,2個互斥一個同步作業似乎腥。 – spectras