54 lines
1.4 KiB
C
54 lines
1.4 KiB
C
|
#include <stdio.h>
|
||
|
#include <pthread.h>
|
||
|
#include <unistd.h>
|
||
|
|
||
|
// 静态初始化互斥锁
|
||
|
// pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
|
||
|
// 动态初始化锁-定义锁
|
||
|
pthread_mutex_t mutex;
|
||
|
|
||
|
void *printer(void *data)
|
||
|
{
|
||
|
|
||
|
char *msg = (char *)data;
|
||
|
int lock_acquired = 0; // 未获取到锁
|
||
|
while (!lock_acquired) // 未获取到锁的时候,循环尝试获取锁,并处理
|
||
|
{
|
||
|
// trylock 非阻塞锁
|
||
|
if (pthread_mutex_trylock(&mutex) == 0) // 如果拿到锁
|
||
|
{
|
||
|
lock_acquired = 1; // 该状态:已获取到锁
|
||
|
while (*msg) // 当前线程传入的字符串未读取完成时,循环读取
|
||
|
{
|
||
|
printf("%c", *msg++);
|
||
|
fflush(stdout);
|
||
|
usleep(200 * 1000);
|
||
|
}
|
||
|
pthread_mutex_unlock(&mutex); // 读完后,解锁当前进程
|
||
|
}
|
||
|
else
|
||
|
{
|
||
|
usleep(100); // 0.1 毫秒后继续尝试获取锁
|
||
|
}
|
||
|
}
|
||
|
return NULL;
|
||
|
}
|
||
|
|
||
|
int main(int argc, char const **argv)
|
||
|
{
|
||
|
// 动态初始化锁-初始化
|
||
|
pthread_mutex_init(&mutex, NULL);
|
||
|
|
||
|
pthread_t tid1, tid2;
|
||
|
pthread_create(&tid1, NULL, printer, "disen666\n");
|
||
|
pthread_create(&tid2, NULL, printer, "lucy888\n");
|
||
|
|
||
|
pthread_join(tid1, NULL);
|
||
|
pthread_join(tid2, NULL);
|
||
|
printf("\n---over---\n");
|
||
|
|
||
|
// 销毁互斥锁
|
||
|
pthread_mutex_destroy(&mutex);
|
||
|
|
||
|
return 0;
|
||
|
}
|