c - 互斥量动态分配

标签 c pthreads mutex

我成功地使用了静态互斥锁,但我在使用动态版本时遇到了问题。 在输出中,变量应等于零.. 请帮忙。 有没有更好的写法?

#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 但在初始化 beerdata->val 时无法使用它,您初始化了 data-> val 但永远不要使用它...

关于c - 互斥量动态分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20019925/

相关文章:

c++ - 使用 pthread 计算平均运行时间,结果很奇怪

c++ - 当超过 12 个线程时,pthread_create 段错误?

c++ - 2 个 pthread 条件变量可以共享同一个互斥锁吗?

c++ - 上下文对象的同步

python - 多进程条件/命名锁

c - 为什么我的C程序无法正确计算和打印文本文件中的整数?

c - 运行c程序时eclipse控制台窗口奇怪的输出

c++ - 在 Cmd 窗口之间切换焦点,强制焦点(保持程序运行的 1 个瞬间)

c - 鲍勃·马丁 : "C has perfect encapsulation" HOW?

c++ - 字符串文字数组中字符串文字的编译时间大小