demo
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <iostream>
using namespace std;
long int a = 0;
pthread_mutex_t mutex;
pthread_mutex_t mutex2;
void* threadFunc(void *arg)
{
// pthread_mutex_lock(&mutex);
for(int i = 0; i < 500000; i++)
{
a = a+1;
}
// pthread_mutex_unlock(&mutex);
// pthread_mutex_lock(&mutex2);
}
void* threadFunc2(void *arg)
{
// pthread_mutex_lock(&mutex2);
for(int i = 500000; i < 1000000; i++)
{
a = a+1;
}
// pthread_mutex_unlock(&mutex2);
// pthread_mutex_lock(&mutex);
}
int main(int argc,char **argv)
{
pthread_t thread1,thread2;
// pthread_create(&thread1 ,NULL, threadFunc,NULL);
pthread_create(&thread1, NULL, threadFunc, NULL);
pthread_create(&thread2 ,NULL, threadFunc2,NULL);
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
cout << "value a = " << a << endl;
return 0;
}
1 多线程编译及调试
# 1 编译生成带符号信息的程序
g++ multhread.cpp -g -lpthread -o test_thread# 2 开始调试程序
gdb ./test_thread
# 3 显示源程序
layout next
此时会显示如下:

输入下面的命令 “r”继续运行程序