本系列浅谈自己接触过的线程和互斥锁,欢迎交流
我对线程的理解就是多条腿走路,但同时也会有一条主腿,虽然这个解释并不恰当,但是读者可以粗略的理解为主腿就是主线程,另外多条腿就是子线程。
通常情况下main函数就是主线程,为了提高cpu的运行效率,充分利用cpu的资源,因此我们常常会调用子线程帮助一起进行计算。
互斥:线程之间可能会发生争抢资源的现象,因此需要进行互斥,即用一把锁锁住一个线程里的函数,直到运行完后解锁,线程再去执行下一个函数。
线程:主线程和子线程在运行时执行完毕的时间是不一定的,主线程在通常要在所有子线程运行完释放资源之后再结束释放,因此就涉及到了本文的函数。
pthread_mutex_init:线程初始化
pthread_join():当前线程阻塞,指导被调用线程结束后,当前线程才开始执行
使用方法:
pthread_t tid;
pthread_create(&tid, NULL, thread_run,NULL);
pthread_join(tid,NULL);
- 头文件
#include <pthread.h>
- 函数原型
int pthread_mutex_init(pthread_mutex_t *restrict_mutex,const pthread_mutexattr_t *restrict_attr);
- 示例对比
下面是两个C++文件,编译命令为:
g++ test.cpp -lpthread -o test
./test
未使用线程锁:
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <iostream>
using namespace std;
int gnum = 0;
static void* thread_fun1(void*)
{
int i = 0;
for (i = 0; i < 3; i++)
{
printf("this is thread1\n");
sleep(1);
gnum++;
printf("thread1 add one to num %d\n", gnum);
}
}
static void* thread_fun2(void*)
{
int i = 0;
for (i = 0; i < 5; i++)
{
printf("this is thread2\n");
sleep(1);
gnum++;
printf("thread2 add one to num %d\n", gnum);
}
}
int main()
{
pthread_t id1, id2;
printf("start\n");
pthread_create(&id1, NULL, thread_fun1, NULL);
pthread_create(&id2, NULL, thread_fun2, NULL);
pthread_join(id1, NULL);
pthread_join(id2, NULL);
printf("end\n");
}
结果:线程1和2非规律的交替运行,实现函数功能。
start
this is thread1
this is thread2
thread2 add one to num 2
this is thread2
thread1 add one to num 1
this is thread1
thread1 add one to num 3
this is thread1
thread2 add one to num 4
this is thread2
thread1 add one to num 5
thread2 add one to num 6
this is thread2
thread2 add one to num 7
this is thread2
thread2 add one to num 8
end
使用线程锁:
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
int gnum = 0;
pthread_mutex_t mutex;
static void* thread_fun1(void*)
{
int i = 0;
for (i = 0; i < 5; i++)
{
pthread_mutex_lock(&mutex);
printf("this is thread1\n");
sleep(1);
gnum++;
printf("thread1 add one to num %d\n", gnum);
pthread_mutex_unlock(&mutex);
}
}
static void* thread_fun2(void*)
{
int i = 0;
for (i = 0; i < 5; i++)
{
pthread_mutex_lock(&mutex);
printf("this is thread2\n");
sleep(1);
gnum++;
printf("thread2 add one to num %d\n", gnum);
pthread_mutex_unlock(&mutex);
}
}
int main()
{
pthread_t id1, id2;
printf("start\n");
pthread_mutex_init(&mutex, NULL);
pthread_create(&id1, NULL, thread_fun1, NULL);
pthread_create(&id2, NULL, thread_fun2, NULL);
pthread_join(id1, NULL);
pthread_join(id2, NULL);
printf("end\n");
}
结果:在主线程中先运行线程1的内容,实现五次循环,再解锁进入线程2里面实现五次循环,解锁释放,主函数结束。
start
this is thread1
thread1 add one to num 1
this is thread1
thread1 add one to num 2
this is thread1
thread1 add one to num 3
this is thread1
thread1 add one to num 4
this is thread1
thread1 add one to num 5
this is thread2
thread2 add one to num 6
this is thread2
thread2 add one to num 7
this is thread2
thread2 add one to num 8
this is thread2
thread2 add one to num 9
this is thread2
thread2 add one to num 10
end