概述
#include <pthread.h>
int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);
销毁int pthread_mutex_destroy(pthread_mutex_t mutex);
// 返回:若成功返回0,否则返回错误编号
#include <pthread.h>
加锁int pthread_mutex_lock(pthread_mutex_t mutex);
加锁不阻塞int pthread_mutex_trylock(pthread_mutex_t mutex);
解锁int pthread_mutex_unlock(pthread_mutex_t mutex);
// 返回:若成功返回0,否则返回错误编号
#include <stdio.h>
#include <pthread.h>
// int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
// void *(*start_routine) (void *), void *arg);
pthread_mutex_t mutex; //创建锁
void *func1(void *str)
{
pthread_mutex_lock(&mutex);
printf("t1:str=%dn",*((int *)str));
printf("t1:id=%ldn",(unsigned long)pthread_self());
pthread_mutex_unlock(&mutex);
}
void *func2(void *str)
{
pthread_mutex_lock(&mutex);
printf("t2:str=%dn",*((int *)str));
printf("t2:id=%ldn",(unsigned long)pthread_self());
pthread_mutex_unlock(&mutex);
}
int main ()
{
int ret;
pthread_t t1 ;
pthread_t t2 ;
int len=100;
int len1=102;
pthread_mutex_init(&mutex,NULL); //初始化锁
ret=pthread_create(&t1,NULL,func1,(void*)&len);
if(ret==0){
printf("main:ptherad t1 create successn");
printf("main:id=%ldn",(unsigned long)pthread_self());
}
ret=pthread_create(&t2,NULL,func2,(void*)&len1);
if(ret==0){
printf("main:ptherad t2 create successn");
printf("main:id=%ldn",(unsigned long)pthread_self());
}
pthread_join(t1,NULL);
pthread_join(t2,NULL);
pthread_mutex_destroy(&mutex);
return 0;
}
最后
以上就是坚定发卡为你收集整理的线程的创建,加锁,解锁销毁锁的全部内容,希望文章能够帮你解决线程的创建,加锁,解锁销毁锁所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复