42 lines
938 B
C
42 lines
938 B
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;
|
||
|
pthread_mutex_lock(&mutex); // 申请上锁,可能阻塞
|
||
|
while (*msg)
|
||
|
{
|
||
|
printf("%c", *msg++);
|
||
|
fflush(stdout);
|
||
|
usleep(200 * 1000);
|
||
|
}
|
||
|
pthread_mutex_unlock(&mutex); // 不解锁,就会发生死锁
|
||
|
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;
|
||
|
}
|