pthread在Linux运行,Linux应用程序错误使用pthread

本文分析了在Linux环境中,由于错误地使用pthread_mutex锁,可能导致程序概率性触发SIG_ABRT信号崩溃的问题。通过示例程序展示了在解锁未加锁的mutex或线程间不正确地同步加解锁操作,如何引发`Assertion `mutex->__data.__owner == 0' failed`错误。解决方案是遵循正确的加解锁流程,或使用条件变量、信号量进行线程同步。
摘要由CSDN通过智能技术生成

本文分析在Linux应用程序中错误使用pthread_mutex锁时会概率性触发SIG_ABRT信号而导致程序崩溃(库打印输出 :Assertion `mutex->__data.__owner == 0' failed)的原因。

程序环境如下:(1)Glibc-2.15 (2)Linux-4.1.12 (3)树莓派1b

首先给出出错的示例程序:

#include

#include

#include "pthread.h"

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

void * process(void * arg)

{

fprintf(stderr, "Starting process %s\n", (char *) arg);

while (1) {

/* 加锁等待某些资源 */

pthread_mutex_lock(&lock);

fprintf(stderr, "Process %s lock mutex\n", (char *) arg);

/* 加锁成功表示资源就绪 */

usleep(1000);

/* do something */

}

return NULL;

}

int main(void)

{

pthread_t th_a, th_b;

int ret = 0;

ret = pthread_create(&th_a, NULL, process, "a");

if (ret != 0) fprintf(stderr, "create a failed %d\n", ret);

ret = pthread_create(&th_b, NULL, process, "b");

if (ret != 0) fprintf(stderr, "create b failed %d\n", ret);

while (1) {

/* 等待并检测某些资源就绪 */

/* something */

/* 解锁告知线程资源就绪 */

pthread_mutex_unlock(&lock);

fprintf(stderr, "Main Process unlock mutex\n");

}

return 0;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值