c - pthread_mutex_lock 在 C 中返回 22

标签 c pthreads

这个问题在这里已经有了答案:





pthread_mutex_lock returns invalid argument

(2 个回答)


6年前关闭。




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

代码如下:

pthread_mutex_lock is used in 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

最佳答案

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

pthread_mutex_init(&mut, NULL);

关于c - pthread_mutex_lock 在 C 中返回 22,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30511046/

相关文章:

c - C 中 pthread 不退出

c - OpenSSL 使用 EVP 与算法 API 进行对称加密

c - 如何给指针赋值

c - 生产者/消费者实现: Stuck in consumer loop

c - 我的 Posix 线程在没有信号的情况下唤醒

c++ - 强制转换为 void* 以将对象传递给 C++ 中的 pthread

multithreading - 为什么我的应用程序没有使用 Mac OS X 上的所有内核?

尽管未使用 Xcode,C 程序仍生成与 Xcode 相关的编译警告

c - 循环遍历其他源文件中定义的数组时出现问题

c - 计算模 25 的高效(循环明智)算法?