我成功地使用了静态互斥锁,但我在使用动态版本时遇到了问题。 在输出中,变量应等于零.. 请帮忙。 有没有更好的写法?
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#define N 20
int beers=20;
void* drink(void*);
//pthread_mutex_t lockk = PTHREAD_MUTEX_INITIALIZER;
typedef struct st1{
pthread_mutex_t mutex;
int val;
}my_struct_t;
int main(){
pthread_t th[N];
int i;
void* return_val;
my_struct_t *data;
data = malloc(sizeof(my_struct_t));
data->val = 20;
pthread_mutex_init(&data->mutex,NULL);
for(i=0;i<N;i++)
pthread_create(&th[i], NULL, drink, &data);
for(i=0;i<N;i++)
pthread_join(th[i], &return_val);
pthread_mutex_destroy(&data->mutex);
printf("%d\n", beers);
}
void* drink(void* p){
int i;
my_struct_t *data = (my_struct_t *)p;
pthread_mutex_lock(&data->mutex);
beers--;
pthread_mutex_unlock(&data->mutex);
//}
return NULL;
}
我在哪里失败了? :)
最佳答案
这里有一个问题:
pthread_create(&th[i], NULL, drink, &data);
您正在传递指针 data
的地址,因此类型为 my_struct_t**
,但将其视为 my_struct_t*
drink
函数。删除调用方中的 &
,代码应该可以工作。
请做一些清理工作。您有未使用的变量,定义了 N
但在初始化 beer
和 data->val
时无法使用它,您初始化了 data-> val
但永远不要使用它...
关于c - 互斥量动态分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20019925/