在linux上使用gdb分析死锁问题

学习1
学习2

死锁代码解读:

#include<bits/stdc++.h>
#include "unistd.h"

using namespace std;

pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex3 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex4 = PTHREAD_MUTEX_INITIALIZER;

static int sequence1 = 0;
static int sequence2 = 0;

int func1() {
  pthread_mutex_lock(&mutex1);
  sequence1++;
  cout << sequence1 << endl;
  sleep(1);
  pthread_mutex_lock(&mutex2);
  sequence2++;
  cout << sequence2 << endl;
  pthread_mutex_unlock(&mutex2);
  pthread_mutex_unlock(&mutex1);
  return sequence1;
}

int func2() {
  pthread_mutex_lock(&mutex2);
  sequence2++;
  cout << sequence2 << endl;
  sleep(1);
  pthread_mutex_lock(&mutex1);
  sequence1++;
  cout << sequence1 << endl;
  pthread_mutex_unlock(&mutex1);
  pthread_mutex_unlock(&mutex2);
  return sequence2;
}

void *thread1(void *arg) {
  while (1) {
    int v = func1();
    cout << v << endl;
    if (v == 100000) {
//      exit thread
      pthread_exit(NULL);
    }
  }
}

void *thread2(void *arg) {
  while (1) {
    int v = func2();
    cout << v << endl;
    if (v == 100000) {
      pthread_exit(NULL);
    }
  }
}

void *thread3(void *arg) {
  while (1) {
    sleep(1);
    char szBuf[128];
    memset(szBuf, 0, sizeof(szBuf));
//    copy string
    strcpy(szBuf, "thread3");
    cout << "thread3 copied" << endl;
  }
}

void *thread4(void *arg) {
  while (1) {
    sleep(1);
    char szBuf[128];
    memset(szBuf, 0, sizeof(szBuf));
    strcpy(szBuf, "thread3");
    cout << "thread4 copied" << endl;
  }
}

int main() {
//  thread array
  pthread_t tid[4];

//  create thread an execute
  if (pthread_create(&tid[0], NULL, &thread1, NULL) != 0) {
    _exit(1);
  }
  if (pthread_create(&tid[1], NULL, &thread2, NULL) != 0) {
    _exit(1);
  }
  if (pthread_create(&tid[2], NULL, &thread3, NULL) != 0) {
    _exit(1);
  }
  if (pthread_create(&tid[3], NULL, &thread4, NULL) != 0) {
    _exit(1);
  }

  sleep(5);

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值