mutex的使用_mutex semaphore区别_c mutex使用(3)

电脑杂谈  发布时间:2017-03-08 13:06:44  来源:网络整理

互斥量用pthread_mutex_t数据类型来表示,在使用互斥量以前,必须首先对它进行初始化,可以把它置为常量PTHREAD_MUTEX_INITIALIZER(只对静态分配的互斥量),也可以通过调用pthread_mutex_init函数进行初始化,如果动态地分配互斥量,那么释放内存前需要调用pthread_mutex_destroy.

二、初始化/回收互斥锁

1.

名称::

pthread_mutexattr_init

功能:

初始化互斥锁。

头文件:

#include <pthread.h>

函数原形:

int pthread_mutex_init(pthread_mutex_t * mutex,

const pthread_mutex_t *attr);

参数:

mutex 互斥量

attr 互斥锁属性

返回值:

若成功则返回0,否则返回错误编号。

mutex是我们要锁住的互斥量,attr是互斥锁的属性,可用相应的函数修改,我们在下章介绍,要用默认的属性初始化互斥量,只需把attr设置为NULL。

对互斥量进行加锁,需要调用pthread_mutex_lock,如果互斥量已经上锁,调用线程阻塞直至互斥量解锁。对互斥量解锁,需要调用pthread_mutex_unlock.

如果线程不希望被阻塞,他可以使用pthread_mutex_trylock尝试对互斥量进行加锁。如果调用pthread_mutex_trylock时互斥量处于未锁住状态,那么pthread_mutex_trylock将锁住互斥量,否则就会失败,不能锁住互斥量,而返回EBUSY。

下面试例子可以证明对互斥量加锁的必要性:

我们先来看不加锁的程序。

#inlcude <stdio.h>

#include <pthread.h>

#inlcude <stdio.h>

#include <unistd.h>

viid *thread_function(void *arg);

int run_now=1; /*用run_now代表共享资源*/

int main()

{

int print_count1=0; /*用于控制循环*/

prhread_t a_thread;

if(pthread_create(&a_thread,NULL,thread_function,NULL)!=0) /*创建一个进程*/

{

perror(“Thread createion failed”);

exit(1);

}

while(print_count1++<5)

{

if(run_now==1) /主线程:如果run_now为1就把它修改为2*/

{

printf(“main thread is run\n”);

run_now=2;

}

else

{

printf(“main thread is sleep\n”);

sleep(1);

}

}

pthread_join(a_thread,NULL); /*等待子线程结束*/

exit(0);

}

void *thread_function(void *arg)

{

int print_count2=0;

while(print_count2++<5)

{

if(run_now==2) /子线程:如果run_now为1就把它修改为1*/

{

printf(“function thread is run\n”);

run_now=1;

}

else


本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/jisuanjixue/article-36452-3.html

相关阅读
    发表评论  请自觉遵守互联网相关的政策法规,严禁发布、暴力、反动的言论

    热点图片
    拼命载入中...