我第一次在 C 中使用執行緒進行“大規模”作業,我不確定如何正確使用多個互斥鎖,每個互斥鎖保護一個結構,并且該結構可能由多個執行緒操作
考慮以下代碼
#include <pthread.h>
#include <stdlib.h>
struct example{
int parameter;
};
void *do_something(void *argument);
int main(){
struct example *ex1 = (struct example *) malloc(sizeof(struct example));
struct example *ex2 = (struct example *) malloc(sizeof(struct example));
ex1->parameter = 5;
ex2->parameter = 4;
pthread_t thread1;
pthread_t thread2;
pthread_t thread3;
pthread_t thread4;
pthread_create(&thread1,NULL, do_something, ex1);
pthread_create(&thread2,NULL, do_something, ex1);
pthread_create(&thread3,NULL, do_something, ex2);
pthread_create(&thread4,NULL, do_something, ex2);
return 0;
}
void *do_something(void *argument){
struct example *something = (struct example *) argument;
something->parameter = something->parameter 1;
return NULL;
}
在上面的代碼中,為 ex1 和 ex2 分配兩個互斥鎖的最佳方法是什么?我有幾個想法,但我不確定哪個會奏效,哪個會造成災難
struct parameters{
struct example *example;
pthread_mutex_t lock;
};
struct parameters *param
pthread_create(&thread1,NULL, do_something, param);
或者甚至可能在第一個結構中包含互斥鎖,所以就像
struct example{
int parameter;
pthread_mutex_t lock;
};
我不確定哪個更好,或者兩者是否都可以使用,我很想在我提交一種方法之前聽到一些意見、指示甚至閱讀建議,結果證明是一場災難
uj5u.com熱心網友回復:
在上面的代碼中,為 ex1 和 ex2 分配兩個互斥鎖的最佳方法是什么?
將單獨的互斥鎖與給定結構型別的每個實體相關聯的最自然方法是使其成為該型別的成員。這并不總是可能的,但是當您以任何其他方式形成關聯時,您很容易遇到如何從給定的結構實體中確定與它相關的互斥鎖的問題。
也就是說,如果struct example您想要互斥鎖,那么
struct example{ int parameter; pthread_mutex_t lock; };
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/462112.html
上一篇:mktime()用于非本地時區
