c - 两个线程,首先添加第二个减法

标签 c pthreads

这是互斥锁的经典例子。我不知道为什么以下代码不起作用,即。它不会每次都打印“ctr = 0”(但是,例如,ctr = 535)。

int ctr;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;

void * add (void * arg_wsk)
{
        int i;
        for (i = 0; i < 100000; i++) {
                pthread_mutex_lock (&m);
                ctr++;
                pthread_mutex_unlock (&m);
        }
        return(NULL);
}

void * sub(void * arg_wsk)
{
        int i;
        for (i = 0; i < 100000; i++) {
                pthread_mutex_lock (&m);
                ctr--;
                pthread_mutex_unlock (&m);
        }
        return(NULL);
}
int main()
{       
        pthread_t tid1, tid2;
        int i;
        void *res;
        ctr = 0;
        pthread_mutex_init(&m, NULL);

        pthread_create(&tid1, NULL, add, NULL);
        pthread_detach(tid1);

        pthread_create(&tid2, NULL, sub, NULL);
        pthread_detach(tid2);

        pthread_join(tid1, &res);
        pthread_join(tid2, &res);

        pthread_mutex_destroy(&m);
        printf("ctr = %d", ctr);
        pthread_exit(NULL);
}

最佳答案

我认为您滥用了 POSIX API。如果你分离线程,你不应该加入它们。删除分离,看看这是否改善了事情。我想您会看到 main() 现在会阻塞,直到线程完成。

另请注意,来自加入通话的链接

ESRCH  No  thread could be found corresponding to that specified by the
          given thread ID.

如果你幸运的话,你会碰到这个的。如果你不走运,疯狂的事情就会发生。不要在同一线程上混合分离和加入调用。

https://computing.llnl.gov/tutorials/pthreads/#Joining

关于c - 两个线程,首先添加第二个减法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22638317/

相关文章:

c - 调用 lseek64 后从文件中读取 - Linux

c - 嵌入式 linux 编程入门套件

C 嵌套结构的默认初始化

c - forkall 没有按预期工作

c库函数获取事件线程数

c - telnet 在发送数据时是否添加任何额外的字节?

使用 OpenSSL 计算并打印文件的 SHA256 哈希值

c - C 基本打印中的 Pthread

c - 将函数名称作为字符指针传递给 C 中的 pthread_create

c - 修复 "undefined reference to"ft. makefile.txt 和 pthreads