返回

linux 互斥锁 1初始化互斥锁 2上锁 3解锁 4销毁互斥锁

发布时间:2022-09-21 19:02:32 316
初始化互斥锁
int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr);

上锁
int pthread_mutex_lock(pthread_mutex_t *mutex);

解锁
int pthread_mutex_unlock(pthread_mutex_t * mutex);

销毁互斥锁
int pthread_mutex_destroy(pthread_mutex_t *mutex);

#include
#include
#include
#include

pthread_mutex_t mutex;
// print
void printer(char *str)
{
pthread_mutex_lock(&mutex);
while(*str!='\0')
{
putchar(*str);
fflush(stdout);
str++;
sleep(1);
}
printf("\n");
pthread_mutex_unlock(&mutex);
}

// thread one
void *thread_fun_1(void *arg)
{
char *str = "hello";
printer(str);
}

// thread two
void *thread_fun_2(void *arg)
{
char *str = "world";
printer(str);
}

int main(void)
{
pthread_t tid1, tid2;
int err1, err2;
pthread_mutex_init(&mutex, NULL);
// creat two thread
err1 = pthread_create(&tid1, NULL, thread_fun_1, NULL);
err2 = pthread_create(&tid2, NULL, thread_fun_2, NULL);
// wait thread end
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
pthread_mutex_destroy(&mutex);
return 0;
}
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像
精选文章
thumb 中国研究员首次曝光美国国安局顶级后门—“方程式组织”
thumb 俄乌线上战争,网络攻击弥漫着数字硝烟
thumb 从网络安全角度了解俄罗斯入侵乌克兰的相关事件时间线
下一篇
有哪些前端面试题是必须要掌握的 2022-09-21 18:37:50