c - 互斥锁永远锁定函数中的一个值

标签 c multithreading pthreads

我是 c 线程的新手。我的代码有一个增加计数器的线程,偶尔(随机)另一个线程读取该计数器。我在这段代码中使用了互斥量,但我的代码总是给我等于 1 的值。虽然我使用了 pthread_mutex_unlock,但似乎该值永远变成了锁。我应该怎么做才能解决这个问题?

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/fcntl.h>
#include <pthread.h>
///////////////////////////

long int count=0;
int RunFlag=0;
pthread_mutex_t mtx;

void *readfun(void *arg)
{
    while (RunFlag==0)
    {
        pthread_mutex_lock(&mtx);
        count=count+1;
        pthread_mutex_unlock(&mtx);
    }

}
void *printfun(void *arg)
{
    int RadnTime=0;
    for (int j=0;j<4;j++)
    {
        RadnTime=rand()%3+1;
        sleep(RadnTime);

        printf("The current counter after %d seconds is: ",RadnTime);
        pthread_mutex_lock(&mtx);
        printf("%d\n",count);
        pthread_mutex_unlock(&mtx);
    }



}

void main ()
{
    pthread_t thread1;
    pthread_t thread2;

    pthread_mutex_init(&mtx, NULL);

    pthread_create(&thread1,NULL,readfun,NULL);
    pthread_create(&thread2,NULL,printfun,NULL);

    //stop the counter
    RunFlag=1;

    pthread_exit(NULL);
}

最佳答案

您正在设置 RunFlag在创建两个线程后立即,所以 readfun几乎没有时间执行。 RunFlag=1;应该在 printfun 的末尾.


据我所知,读取和写入RunFlag不保证是原子的,所以对它的访问也应该受到保护。我没有看到这里发生问题(考虑到有问题的值),但您正在进入未定义的行为领域。


即使声明为返回 void*,您的函数也不会返回任何内容.添加return NULL;给他们。


最后,第二个%d应该是 %ldcountlong int .


注意

pthread_mutex_t mtx;
pthread_mutex_init(&mtx, NULL);

可以替换为

pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;

关于c - 互斥锁永远锁定函数中的一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41127460/

相关文章:

c - 代码片段的说明(结构)

java - 并发还是顺序?

java - 从技术上讲,什么是数据库连接?

c - 如何在有关多线程的 C 代码中使用信号量

c++ - C++中的Pthread取消

c - 为什么运行时上下文在为 10g 编译的程序中不能在 11g 上工作?

将任意大小的字符串转换为任意精度的整数(bigint)

c - 将变量移动到 cl 并使用内联汇编执行 shr

c - 如何获得终端窗口宽度?

vb.net - 委托(delegate),开始调用。 EndInvoke - 如何清除对同一委托(delegate)的多个异步威胁调用?