1、关于互斥锁的函数
// 初始化互斥锁。attr 一般为 NULL
// 静态初始化:pthread_mutex_t mymutex= PTHREAD_MUTEX_INITIALIZER;
int pthread_mutex_init(pthread_mutex_t * mutex , pthread_mutexattr_t * attr);
// 销毁互斥锁
int pthread_mutex_destroy (pthread_mutex_t * mutex);
// 加锁 - 阻塞
int pthread_mutex_lock (pthread_mutex_t * mutex );
// 解锁
int pthread_mutex_unlock (pthread_mutex_t * mutex );
// 加锁 - 非阻塞
int pthread_mutex_trylock (pthread_mutex_t * mutex );
2、静态实现
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
void* test(void *arg)
{
pthread_mutex_t *mutex = (pthread_mutex_t *)arg;
printf("wait...\n");
pthread_mutex_lock(mutex); // 加锁
printf("[test()] hello \n");
pthread_mutex_unlock(mutex); // 解锁
pthread_exit((void *)0);
}
int main(void)
{
pthread_t thread_id;
// 静态分配:需要再声明的时候直接初始化,下面分开的做法是错误的
// pthread_mutex_t mymutex;
// mymutex= PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mymutex= PTHREAD_MUTEX_INITIALIZER;
printf("[main()] main func !\n");
pthread_mutex_lock(&mymutex); // 加锁
if (0 == pthread_create(&thread_id, NULL, (void *)test, (void *)(&mymutex))){
printf("[main()] created thread~\n");
}else{
printf("[main()] create error\n");
}
sleep(1);
printf("wait...\n");
pthread_mutex_unlock(&mymutex); // 解锁
pthread_join(thread_id, NULL);
return 0;
}
输出如下,先创建线程,然后 wait,等 please wait... 完后主线程解锁,然后才 say hello:
[main()] main func !
[main()] created thread~
wait...
please wait...
[test()] hello
3、动态实现,手动释放
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
void* test(void *arg)
{
pthread_mutex_t *mutex = (pthread_mutex_t *)arg;
printf("wait...\n");
pthread_mutex_lock(mutex);
printf("[test()] hello \n");
pthread_mutex_unlock(mutex);
pthread_exit((void *)0);
}
int main(void)
{
pthread_t thread_id;
pthread_mutex_t mymutex;
// 动态分配:需要手动释放
pthread_mutex_init(&mymutex, NULL);
printf("[main()] main func !\n");
pthread_mutex_lock(&mymutex);
if (0 == pthread_create(&thread_id, NULL, (void *)test, (void *)(&mymutex))){
printf("[main()] created thread~\n");
}else{
printf("[main()] create error\n");
}
sleep(1);
printf("please wait...\n");
pthread_mutex_unlock(&mymutex);
pthread_join(thread_id, NULL);
// 手动释放
pthread_mutex_destroy(&mymutex);
return 0;
}
4、还有很多情况,后面再慢慢了解
还有死锁问题.
PTHREAD_MUTEX_INITIALIZER // 创建快速互斥锁。
PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP // 创建递归互斥锁。
PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP // 创建检错互斥锁
[reference]
[1] wtz1985. linux多线程学习(四)——互斥锁线程控制[M]. (2009年01月17日 21:24:00). http://blog.csdn.net/wtz1985/article/details/3819052