线程同步的方法有哪些?Linux下实现线程同步的三种方法
时间:2021-07-01 10:21:17
帮助过:10人阅读
线程同步的方法有哪些?在linux下,系统提供了很多种方式来实现线程同步,其中最常用的便是互斥锁、条件变量和信号量这三种方式,可能还有很多伙伴对于这三种方法都不熟悉,下面就给大家详细介绍下。
Linux下实现线程同步的三种方法:
一、互斥锁(mutex)
通过锁机制实现线程间的同步。
1、初始化锁。在Linux下,线程的互斥量数据类型是pthread_mutex_t。在使用前,要对它进行初始化。
静态分配:pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
动态分配:int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutex_attr_t *mutexattr);
2、加锁。对共享资源的访问,要对互斥量进行加锁,如果互斥量已经上了锁,调用线程会阻塞,直到互斥量被解锁。
int pthread_mutex_lock(pthread_mutex *mutex);
int pthread_mutex_trylock(pthread_mutex_t *mutex);
3、解锁。在完成了对共享资源的访问后,要对互斥量进行解锁。
int pthread_mutex_unlock(pthread_mutex_t *mutex);
4、销毁锁。锁在是使用完成后,需要进行销毁以释放资源。
int pthread_mutex_destroy(pthread_mutex *mutex);
- 01#include <cstdio>
- 02#include <cstdlib>
- 03#include <unistd.h>
- 04#include <pthread.h>
- 05#include "iostream"
- 06using namespace std;
- 07pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
- 08int tmp;
- 09void* thread(void *arg)
- 10{
- 11cout << "thread id is " << pthread_self() << endl;
- 12pthread_mutex_lock(&mutex);
- 13tmp = 12;
- 14cout << "Now a is " << tmp << endl;
- 15pthread_mutex_unlock(&mutex);
- 16return NULL;
- 17}
- 18int main()
- 19{
- 20pthread_t id;
- 21cout << "main thread id is " << pthread_self() << endl;
- 22tmp = 3;
- 23cout << "In main func tmp = " << tmp << endl;
- 24if (!pthread_create(&id, NULL, thread, NULL))
- 25{
- 26cout << "Create thread success!" << endl;
- 27}
- 28else
- 29{
- 30cout << "Create thread failed!" << endl;
- 31}
- 32pthread_join(id, NULL);
- 33pthread_mutex_destroy(&mutex);
- 34return 0;
- 35}
- 36//编译:g++ -o thread testthread.cpp -lpthread
复制代码
#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include <pthread.h>
#include "iostream"
using namespace std;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int tmp;
void* thread(void *arg)
{
cout << "thread id is " << pthread_self() << endl;
pthread_mutex_lock(&mutex);
tmp = 12;
cout << "Now a is " << tmp << endl;
pthread_mutex_unlock(&mutex);
return NULL;
}
int main()
{
pthread_t id;
cout << "main thread id is " << pthread_self() << endl;
tmp = 3;
cout << "In main func tmp = " << tmp << endl;
if (!pthread_create(&id, NULL, thread, NULL))
{
cout << "Create thread success!" << endl;
}
else
{
cout << "Create thread failed!" << endl;
}
pthread_join(id, NULL);
pthread_mutex_destroy(&mutex);
return 0;
}
//编译:g++ -o thread testthread.cpp -lpthread