pthread的pthread_mutex_lock 的使用

本文通过两个C语言多线程示例介绍了如何在多线程环境下避免数据竞争问题。第一个示例展示了无锁情况下多线程打印字符时产生的乱序现象;第二个示例通过使用互斥锁实现了有序打印。
参考http://haoningabc.iteye.com/blog/1709157
在c中多线程,打印数据互相不影响的例子
关键点在pthread_mutex_lock
无锁的情况
testptread.c

#include <stddef.h>
#include <stdio.h>
#include <unistd.h>
#include "pthread.h"

void * process(void * arg)
{
int i;
fprintf(stderr, "Starting process %s\n", (char *) arg);
for (i = 0; i < 100; i++) {
write(1, (char *) arg, 1);
// fprintf(stdout, (char *) arg, 1);
}
return NULL;
}
int hello(){
printf("hello");
return 1;
}
int main()
{
int retcode;
pthread_t th_a, th_b;
void * retval;

retcode = pthread_create(&th_a, NULL, process, "a");
if (retcode != 0) fprintf(stderr, "create a failed %d\n", retcode);

retcode = pthread_create(&th_b, NULL, process, "b");
if (retcode != 0) fprintf(stderr, "create b failed %d\n", retcode);

retcode = pthread_join(th_a, &retval);
if (retcode != 0) fprintf(stderr, "join a failed %d\n", retcode);

retcode = pthread_join(th_b, &retval);
if (retcode != 0) fprintf(stderr, "join b failed %d\n", retcode);

return 0;
}

编译:

#!/bin/sh
gcc testptread.c -lpthread

输出结果
[img]http://dl2.iteye.com/upload/attachment/0094/2116/faafbc57-3836-3d2b-b32c-f03758ecda5e.jpg[/img]
a和b的打印每次输出都是不同的乱序的
-------------------------------
带锁的thread
testptread_lock.c

#include <stddef.h>
#include <stdio.h>
#include <unistd.h>
#include "pthread.h"
pthread_mutex_t mymutex=PTHREAD_MUTEX_INITIALIZER;
void * process(void * arg)
{
int i;
fprintf(stderr, "Starting process %s\n", (char *) arg);
pthread_mutex_lock(&mymutex);
for (i = 0; i < 100; i++) {
write(1, (char *) arg, 1);
// fprintf(stdout, (char *) arg, 1);
}
pthread_mutex_unlock(&mymutex);
return NULL;
}
int hello(){
printf("hello");
return 1;
}
int main()
{
int retcode;
pthread_t th_a, th_b;
void * retval;

retcode = pthread_create(&th_a, NULL, process, "a");
if (retcode != 0) fprintf(stderr, "create a failed %d\n", retcode);

retcode = pthread_create(&th_b, NULL, process, "b");
if (retcode != 0) fprintf(stderr, "create b failed %d\n", retcode);

retcode = pthread_join(th_a, &retval);
if (retcode != 0) fprintf(stderr, "join a failed %d\n", retcode);

retcode = pthread_join(th_b, &retval);
if (retcode != 0) fprintf(stderr, "join b failed %d\n", retcode);

return 0;
}

[img]http://dl2.iteye.com/upload/attachment/0094/2118/da58dee3-75ad-37b1-ab6d-bcc71f53a573.jpg[/img]

无论a,b是什么时候开始,一定是一个结束之后,锁释放后, 第二个才开始
------------------------------
如果上面的访问用进程实现
则用如下
[img]http://dl2.iteye.com/upload/attachment/0094/2130/b18ecadd-446a-3c15-9064-aac7c7e5a38b.jpg[/img]


#include <stdio.h>
char buf[]={"check lock!\n"};
int main(int argc,char *argv[]){
int i,p1,p2,fd;
fd=creat("lock.dat",0644);
write(fd,buf,20);
while((p1=fork())==-1);
if(p1==0){
lockf(fd,1,0);
for(i=1;i<=3;i++){
printf("child1!\n");
}
lockf(fd,0,0);
}else{
while((p2=fork())==-1);
if(p2==0){
lockf(fd,1,0);
for(i=1;i<=4;i++){
printf("child2!\n");
}
lockf(fd,0,0);
}else{
printf("parrent!\n");
}
}
close(fd);
}
pthread_mutex_lockpthread_mutex_trylock主要区别在于阻塞特性。pthread_mutex_lock是阻塞的,当线程使用该函数去锁定一个锁时,若此锁已被其他线程锁住,该线程会被挂起,需等待锁被释放后,才会继续执行锁定操作。例如,A线程去lock一个被其他线程锁住的锁时,A线程会进入等待状态,直至锁被释放再进行lock操作[^1]。 而pthread_mutex_trylock是非阻塞的。该函数进行尝试加锁,即便锁已被其他线程占用,线程也不会被挂起,而是会立即返回。其头文件为 `#include <pthread.h>`,`pthread_mutex_trylock` 接收一个指向待尝试加锁的互斥锁变量地址作为参数,成功时返回0,失败则返回错误码[^1][^3]。 在作用上,`pthread_mutex_lock` 函数确保同一时间只有一个线程能进入 “被锁保护的代码段”(临界区),避免多线程同时操作共享资源导致的数据混乱。其参数是指向已初始化的互斥锁的指针,成功获取锁时返回0,失败返回非0错误码。而 `pthread_mutex_trylock` 用于尝试获取锁,可让线程在获取不到锁时继续执行其他任务,不会像 `pthread_mutex_lock` 那样被阻塞等待,可依此实现一些非阻塞逻辑[^1][^3][^4]。 ### 代码示例 ```c #include <pthread.h> #include <stdio.h> #include <unistd.h> pthread_mutex_t mutex; void* thread_function(void* arg) { // 尝试加锁 int result = pthread_mutex_trylock(&mutex); if (result == 0) { printf("Thread: Lock acquired successfully.\n"); // 模拟一些工作 sleep(2); pthread_mutex_unlock(&mutex); printf("Thread: Lock released.\n"); } else { printf("Thread: Failed to acquire lock.\n"); } return NULL; } int main() { // 初始化互斥锁 pthread_mutex_init(&mutex, NULL); // 主线程先加锁 pthread_mutex_lock(&mutex); printf("Main: Lock acquired.\n"); pthread_t thread; pthread_create(&thread, NULL, thread_function, NULL); // 模拟一些工作 sleep(3); // 主线程释放锁 pthread_mutex_unlock(&mutex); printf("Main: Lock released.\n"); // 等待子线程结束 pthread_join(thread, NULL); // 销毁互斥锁 pthread_mutex_destroy(&mutex); return 0; } ``` ### 代码解释 - 在上述代码中,主线程先使用 `pthread_mutex_lock` 获取锁,子线程使用 `pthread_mutex_trylock` 尝试获取锁。由于锁已被主线程持有,子线程调用 `pthread_mutex_trylock` 会失败并输出提示信息。 - 当主线程释放锁后,这体现了两者的区别:`pthread_mutex_lock` 会阻塞等待,而 `pthread_mutex_trylock` 不会阻塞,会立即返回结果。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值