首先,我是意大利人,對於我的英語不好,感到抱歉。
無論如何,我應該這樣做:
「在C中編寫一個生成線程的程序,主要顯示從1到9的奇數,線程顯示從2到10的偶數。使主線程和線程同步信號燈」
我寫這樣的僞代碼:信號量在C.中不起作用爲什麼?
//semaphores
semParent = free
semChild = busy
main
generate thread "child"
for i=1 to 9 step 2
P(semParent)
print i
V(semChild)
end for
end main
child
for i=2 to 10 step 2
P(semChild)
print i
V(semParent)
end child
這就是我如何用C語言實現:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
pthread_mutex_t semParent;
pthread_mutex_t semChild = PTHREAD_MUTEX_INITIALIZER;
void* functionChild (void* arg) {
for(int i=2; i<=10; i+=2) {
pthread_mutex_lock(&semChild);
printf("CHILD: %d\n",i);
pthread_mutex_unlock(&semParent);
}
return NULL;
}
int main(void) {
pthread_t child;
pthread_create(&child, NULL, &functionChild, NULL);
pthread_mutex_init(&semParent, NULL);
for(int i=1; i<=9; i+=2) {
pthread_mutex_lock(&semParent);
printf("PARENT : %d\n",i);
pthread_mutex_unlock(&semChild);
}
pthread_join(child, NULL);
}
但輸出ALWA每當我運行程序時,ys都會有所不同。
有什麼問題?
我在Windows 10 64位中使用CygWin64終端。
在此先感謝。
爲了實現單調增加的輸出值,您應該將「stick」從一個線程反覆傳遞給其他線程。尋找條件變量。 – Sergio
@Serhio爲什麼他會使用條件變量,如果問題要求他使用信號量?他的僞代碼沒問題,只是C語言翻譯錯了。 –
@PaoloBonzini互斥量經常被視爲二進制信號量(只有兩個計數器值:1或0),因此IMO翻譯是相當合法的。因爲互斥體不提供這種能力,所以需要條件變量來「解凍」等待線程。 – Sergio