互斥动态分配

时间:2013-11-16 15:07:41

标签: 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;
}

我失败的地方? :)

1 个答案:

答案 0 :(得分:2)

这里有一个问题:

pthread_create(&th[i], NULL, drink, &data);

您正在传递指针data的地址,因此类型为my_struct_t**,但在my_struct_t*函数中将其视为drink。删除调用者中的&,代码应该可以正常工作。

请做一些清理工作。您有未使用的变量,定义N但在初始化beerdata->val时无法使用它,您初始化data->val但从不使用它...