我正在學習如何在 Ubuntu 上使用執行緒和信號量在 C 中編程。我想制作一個執行數學運算的程式,例如加法、多重運算……我已經宣告了兩個信號量:互斥互斥和私有(私有 sem)的互斥量,我使用了私有的,這樣 P4 就不會執行,只要 P4 是最后一個函式,哪個函式首先起作用并不重要。我有四個功能:P1:
void *P1(void *arg, int A, int B){
sem_wait(&mutex);
S1 = A B;
printf("S1= %d", S1);
sem_post(&prive);
pthread_exit(NULL);
}
P2:
void *P2(void *arg, int A){
sem_wait(&mutex);
S2 = A 4;
printf("S2= %d", S2);
sem_post(&prive);
pthread_exit(NULL);
}
P3:
void *P3(void *arg, int S2){
sem_wait(&mutex);
S3 = S2 * 2;
sem_post(&prive);
pthread_exit(NULL);
}
P4:
void *P4(void *arg, int S3, int S2){
sem_wait(&prive);
sem_wait(&prive);
S4 = S2 S3;
sem_post(&mutex);
sem_post(&mutex);
pthread_exit(NULL);
}
我已經制作了該程式,但它顯示以下錯誤訊息:
TP4_EXO3.c:在函式'main'中:TP4_EXO3.c:24:1:警告:從不兼容的指標型別傳遞'pthread_create'的引數3 [默認啟用] pthread_create(&TID1,NULL,P1,NULL);^ 在 TP4_EXO3.c:3:0 包含的檔案中:/usr/include/pthread.h:244:12:注意:預期為 'void * (*)(void )' 但引數型別為 'void * ( )( void *, int, int)' extern int pthread_create (pthread_t *__restrict __newthread, //TID2, TID3, TID4 相同// ^
TP4_EXO3.c:在頂層:TP4_EXO3.c:57:7:錯誤:“P3”的型別沖突 void *P3(void *arg, int S2){ ^ TP4_EXO3.c:8:7:注意:先前的宣告'P3' 在這里是 void *P3(void *arg, int S1, int S2); ^
我想讓我的程式輸入 2 個變數并執行函式,如何解決這些問題?
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<semaphore.h>
void *P1(void *arg, int A, int B);
void *P2(void *arg, int A);
void *P3(void *arg, int S1, int S2);
void *P4(void *arg, int S3, int S2);
sem_t mutex, prive;
int S1 = 0, S2 = 0, S3 = 0, S4 = 0;
int A = 15;
int B = 10;
int main(){
pthread_t TID1, TID2, TID3, TID4;
printf("Main: ");
sem_init(&mutex, 0, 1);
sem_init(&prive, 0, 0);
pthread_create(&TID1, NULL, P1, NULL);
pthread_create(&TID2, NULL, P2, NULL);
pthread_create(&TID3, NULL, P3, NULL);
pthread_create(&TID4, NULL, P4, NULL);
pthread_join(TID1, NULL);
pthread_join(TID2, NULL);
pthread_join(TID3, NULL);
pthread_join(TID4, NULL);
sem_destroy(&mutex);
sem_destroy(&prive);
printf("S4= %d", S4);
}
uj5u.com熱心網友回復:
這些pthread_create呼叫中的最后一個引數
pthread_create(&TID1, NULL, P1, NULL);
pthread_create(&TID2, NULL, P2, NULL);
pthread_create(&TID3, NULL, P3, NULL);
pthread_create(&TID4, NULL, P4, NULL);
應該是一個指向結構的指標,該結構包含您希望該函式能夠訪問和使用的任何引數。
P1 函式的示例
struct P1_args {
//void *arg;
int A;
int B;
};
然后在你的void *P1(void *arg, int A, int B)功能
void *P1(void *arg){
struct P1_args *args = arg;
sem_wait(&mutex);
S1 = args->A args->B;
printf("S1= %d", S1);
sem_post(&prive);
pthread_exit(NULL);
}
然后在你的主要功能中你可以做
// ...
struct P1_args p1args = { .A = 1, .B = 2 };
pthread_create(&TID1, NULL, P1, &p1args);
// ...
pthread_join(TID1, NULL);
// ...
至于你關于
TP4_EXO3.c:在頂層:TP4_EXO3.c:57:7:錯誤:“P3”的型別沖突 void *P3(void *arg, int S2){ ^ TP4_EXO3.c:8:7:注意:先前的宣告'P3' 在這里是 void *P3(void *arg, int S1, int S2); ^
您已使用不同的簽名宣告了 P3。
我還看到您使用互斥鎖和信號量時可能出現的一些問題。如果我沒記錯的話,你的函式看起來永遠不會通過sem_wait呼叫。可能是錯的。如果是這種情況,請使用sem_try_wait.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/520374.html
