线程同步
Posted xumaomao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线程同步相关的知识,希望对你有一定的参考价值。
互斥锁(互斥量)
创建互斥锁
pthread_mutex_t mutex;
初始化互斥锁
pthread_mutex_init(pthread_mutex_t* mutex,
const pthread_mutexattr_t* attr
);
销毁互斥锁
pthread_mutex_unlock(pthread_mutex_t *mutex);
加锁
//如果加锁的时候发现锁已经被锁上了,线程会一直阻塞在这个位置
pthread_mutex_lock(pthread_mutex_t *mutex);
//尝试加锁,失败返回,不阻塞
pthread_mutex_trylock(pthread_mutex_t *mutex);
解锁
pthread_mutex_unlock(pthread_mutex_t *mutex);
实例
#include <stdio.h> #include <signal.h> #include <unistd.h> #include <string.h> #include <pthread.h> #define MAX 10000 int number; //创建一把互斥锁 pthread_mutex_t mutex; void* funcA_num(void* arg) { int i; for(i=0; i<MAX; i++) { //加锁 pthread_mutex_lock(&mutex); int cur = number; cur++; number = cur; printf("Thread A, id = %lu, number = %d ", pthread_self(), number); //解锁 pthread_mutex_unlock(&mutex); usleep(10); } return NULL; } void* funcB_num(void* arg) { int i; for(i=0; i<MAX; i++) { //加锁 pthread_mutex_lock(&mutex); int cur = number; cur++; number = cur; printf("Thread B, id = %lu, number = %d ", pthread_self(), number); //解锁 pthread_mutex_unlock(&mutex); usleep(10); } return NULL; } int main(int argc, const char* argv[]) { pthread_t p1, p2; //初始化互斥锁 pthread_mutex_init(&mutex, NULL); //创建两个子进程 pthread_create(&p1, NULL, funcA_num, NULL); pthread_create(&p2, NULL, funcB_num, NULL); //阻塞,回收资源 pthread_join(p1, NULL); pthread_join(p2, NULL); //释放互斥锁资源 pthread_mutex_destroy(&mutex); return 0; }
以上是关于线程同步的主要内容,如果未能解决你的问题,请参考以下文章