我的程式必須嚴格地增加一個計數器,或者使用 2 個執行緒并使用管道檔案同步它們。我知道這沒有任何意義,但這是大學的任務。例如,如果我用 CodeBlocks 運行它,問題就解決了,但是當我從 linux 終端執行程式時它不列印任何東西,我不知道為什么。任何的想法?這是我的代碼:
#include <stdlib.h>
#include <pthread.h>
#include <wait.h>
#include <unistd.h>
#include <string.h>
int contor;
int fd[2];
void* thread_function(void* arg) {
int* th = (int*)arg;
char x = 'x';
while(1)
{
if (*th == 0 && contor % 2 == 0 && contor < 100) {
close(fd[0]);
write(fd[1], &x, 1);
contor ;
printf("Counter: %d incremented by thread: %ld\n", contor, pthread_self());
sleep(0);
if (contor >= 100)
{
pthread_exit(NULL);
}
} else if (*th == 1 && contor % 2 == 1 && contor < 100){
close(fd[1]);
read(fd[0], &x, 1);
contor ;
printf("Counter: %d incremented by thread: %ld\n", contor, pthread_self());
if (contor >= 100)
{
pthread_exit(NULL);
}
}
if (contor >= 100)
{
pthread_exit(NULL);
}
}
}
void main(int argc, char** argv) {
int tr1 = 0;
int tr2 = 0;
pthread_t t1, t2;
int th0 = 0;
pipe(fd);
tr1 = pthread_create(&t1, NULL, &thread_function, (void*)&th0);
if (tr1) {
printf("Error creating thread #1!");
}
int th1 = 1;
tr2 = pthread_create(&t2, NULL, &thread_function, (void*)&th1);
if (tr2) {
printf("Error creating thread #2!");
}
pthread_join(t1, NULL);
pthread_join(t2, NULL);
}
我使用以下方法編譯檔案: gcc -o ex.exe ex.c -lpthread
我使用以下方法執行可執行檔案:./ex.exe
uj5u.com熱心網友回復:
檔案描述符由行程的所有執行緒共享。您的一個執行緒正在關閉管道的一端 ( fd[0]) 并寫入管道的另一端 ( fd[1])。您的另一個執行緒正在關閉管道的另一端 ( fd[1]) 并讀取管道的另一端 ( fd[0])。while此外,它們在一個回圈中被多次關閉。
擺脫close(fd[0])andclose(fd[1])呼叫thread_function會有所幫助。可能還有其他問題,因為在我嘗試時thread_function計數器達到該值后程式停止產生輸出。3
提示:使用兩個管道。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/475218.html
