【问题标题】:pthread_mutex_lock returns 22 in C [duplicate]pthread_mutex_lock 在 C 中返回 22 [重复]
【发布时间】:2015-05-28 15:33:56
【问题描述】:

我正在学习如何在 C 中使用 Pthread。我尝试使用 pthread_mutex_lock。锁定成功时应该返回 0。但我的程序总是返回 22 - 无效参数。

代码如下:

pthread_mutex_lock 用于work_function

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

#define N 2

void *work_function(void *param);

int count=0;
pthread_mutex_t mut;

int main(int args, char **argv)
{
    pthread_t tid[N];
    long int iterations = atoi(argv[1]);

    pthread_create(&tid[0], NULL, work_function, (void *) iterations);
    pthread_create(&tid[1], NULL, work_function, (void *) iterations);

    pthread_join(tid[1], NULL);
    pthread_join(tid[0], NULL);

    if (count != iterations * 2)
        printf("Error: %d\n",count);
    else
        printf("Value as expected: count = %d\n", count);

    pthread_exit(NULL);
}

void *work_function(void *param)
{
    long int max_iter = (long int) param;
    int i, tmp;

    pid_t pid = getpid();
    pthread_t id = pthread_self();

    i = pthread_mutex_lock(&mut);
    printf("%d\n", i);
    for(i = 0; i < max_iter; i++) {
        tmp = count;
        tmp ++;
        printf("in thread: pid=%d and id=%u count=%d new\n", (unsigned int) pid, (unsigned int) id, count);
        // sleep(1);
        count = tmp;
        printf("haha\n");
    }
    pthread_mutex_unlock(&mut);

    pthread_exit(NULL); 
}

3 作为命令行参数传入时会产生以下结果。

22
22
in thread: pid=36767 and id=6819840 count=0 new
in thread: pid=36767 and id=7356416 count=0 new
haha
haha
in thread: pid=36767 and id=6819840 count=1 new
in thread: pid=36767 and id=7356416 count=1 new
haha
haha
in thread: pid=36767 and id=6819840 count=2 new
in thread: pid=36767 and id=7356416 count=2 new
haha
haha
Error: 3

【问题讨论】:

  • pthead_mutex_init(&mut, NULL); ?或尝试使用与 'i' 不同的变量名(这样您就不会双重使用同一个局部变量,因为它被用于 for(;;) 循环计数器,检查编译器问题)
  • @DarrylMiles,非常感谢,Darryl。将pthead_mutex_init(&amp;mut, NULL); 放在main 方法下解决了我的问题。我看了另一个问题,但找不到如何初始化pthread_mutex_t。现在完美运行。

标签: c pthreads


【解决方案1】:

初始化pthread_mutex_t mut 解决了我的问题,将以下代码放在main 方法下。

pthread_mutex_init(&mut, NULL);

【讨论】:

  • 由于您的互斥锁具有静态存储持续时间,您可以使用提供的静态初始化程序来代替:pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
猜你喜欢
  • 1970-01-01
  • 2012-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-06
  • 2013-09-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多