59 lines
1.3 KiB
C
59 lines
1.3 KiB
C
|
#include <stdio.h>
|
||
|
#include <pthread.h>
|
||
|
#include <unistd.h>
|
||
|
|
||
|
// 定义两把锁
|
||
|
pthread_mutex_t mutex1, mutex2;
|
||
|
|
||
|
void *task1(void *data)
|
||
|
{
|
||
|
char *taskName = (char *)data;
|
||
|
pthread_mutex_lock(&mutex1);
|
||
|
printf("%s 获取锁 1 成功, 等待 1 秒后获取锁 2\n", taskName);
|
||
|
sleep(1);
|
||
|
pthread_mutex_lock(&mutex2);
|
||
|
printf("%s 获取锁 2 成功\n", taskName);
|
||
|
printf("%s\n", taskName);
|
||
|
|
||
|
// 释放锁
|
||
|
pthread_mutex_unlock(&mutex2);
|
||
|
pthread_mutex_unlock(&mutex1);
|
||
|
return NULL;
|
||
|
}
|
||
|
|
||
|
void *task2(void *data)
|
||
|
{
|
||
|
char *taskName = (char *)data;
|
||
|
pthread_mutex_lock(&mutex1);
|
||
|
printf("%s 获取锁 1 成功, 等待 1 秒后获取锁 2\n", taskName);
|
||
|
sleep(1);
|
||
|
pthread_mutex_lock(&mutex2);
|
||
|
printf("%s 获取锁 2 成功\n", taskName);
|
||
|
printf("%s\n", taskName);
|
||
|
|
||
|
// 释放锁
|
||
|
pthread_mutex_unlock(&mutex2);
|
||
|
pthread_mutex_unlock(&mutex1);
|
||
|
return NULL;
|
||
|
}
|
||
|
|
||
|
int main(int argc, char const *argv[])
|
||
|
{
|
||
|
// 动态初始化锁
|
||
|
pthread_mutex_init(&mutex1, NULL);
|
||
|
pthread_mutex_init(&mutex2, NULL);
|
||
|
|
||
|
// 创建线程
|
||
|
pthread_t tid1, tid2;
|
||
|
pthread_create(&tid1, NULL, task1, "hello");
|
||
|
pthread_create(&tid2, NULL, task2, "world");
|
||
|
pthread_join(tid1, NULL);
|
||
|
pthread_join(tid2, NULL);
|
||
|
|
||
|
// 销毁锁
|
||
|
pthread_mutex_destroy(&mutex1);
|
||
|
pthread_mutex_destroy(&mutex2);
|
||
|
|
||
|
return 0;
|
||
|
}
|