我有4個處理叫做A,B,C,D在4個線程中,他們printf他們的名字。我想用互斥體來處理A,B,C,D按順序A,B,C,D運行。這是我的代碼,但它不起作用,例如我認爲。他們如何工作?如何在C中使用互斥鎖進行多線程?
#include <stdio.h>
#include <pthread.h>
void processA();
void processB();
void processC();
void processD();
pthread_mutex_t mutex;
void main(){
pthread_t thread1;
pthread_t thread2;
pthread_t thread3;
pthread_t thread4;
pthread_mutex_init(&mutex,NULL);
pthread_create(&thread1, NULL, (void *)&processA,NULL);
pthread_create(&thread2, NULL, (void *)&processB,NULL);
pthread_create(&thread3, NULL, (void *)&processC,NULL);
pthread_create(&thread4, NULL, (void *)&processD,NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
pthread_join(thread3, NULL);
pthread_join(thread4, NULL);
pthread_mutex_destroy(&mutex);
}
void processA()
{
while (1)
{
pthread_mutex_lock(&mutex);
printf("A \n");
pthread_mutex_unlock(&mutex);
}
}
void processB()
{
while (1)
{
pthread_mutex_lock(&mutex);
printf("B \n");
pthread_mutex_unlock(&mutex);
}
}
void processC()
{
while (1)
{
pthread_mutex_lock(&mutex);
printf("C \n");
pthread_mutex_unlock(&mutex);
}
}
void processD()
{
pthread_mutex_lock(&mutex);
while (1)
{
pthread_mutex_lock(&mutex);
printf("D \n");
pthread_mutex_unlock(&mutex);
}
}
你無法控制哪個線程先運行。您需要找出一些其他方式來同步這些線程。條件變量可能?或者如果需要使用這些互斥體,可以使用多個互斥體? –
如果你希望你的進程「按順序」運行,你不需要線程或互斥體。互斥體用於防止多個線程寫入相同的位置,沒有別的。 – DeiDei
在不相關的說明上:void processA();聲明不聲明一個不帶參數的函數'processA'。它聲明瞭一個函數,它接受未定義數量的未知參數。如果你想明確地說一個函數沒有參數,那麼你需要使用'void processA(void);' –