- 0
- 0
- 约1.84万字
- 约 12页
- 2023-04-25 发布于上海
- 举报
Disclaimer :
Disclaimer : The original version of this article was first published on IBM developerWorks, and is property of Westtech Information Services. This document is an updated version of the original article, and contains various improvements made by the Gentoo Linux Documentation team.
This document is not actively maintained.
POSIX threads explained, part 2
Content:
The little things called mutexes Mutex me!
In my previous article, I talked about threaded code that did unusual and unexpected things. Two threads each incremented a global variable twenty times. The variable was supposed to end up with a value of 40, but ended up with a value of 21 instead. What happened? The problem occurred because one thread repeatedly cancelled out the increment performed by the other thread. Lets take a look at some corrected code that uses a mutex to solve the problem:
Code Listing 1.1: thread3.c
Code Listing 1.1: thread3.c
#include pthread.h #include stdlib.h #include unistd.h #include stdio.h
int myglobal;
pthread_mutex_t mymutex=PTHREAD_MUTEX_INITIALIZER;
void *thread_function(void *arg) {
int i,j;
for ( i=0; i20; i++ ) { pthread_mutex_lock(mymutex); j=myglobal;
j=j+1; printf(.); fflush(stdout); sleep(1); myglobal=j;
pthread_mutex_unlock(mymutex);
}
}
return NULL;
}
int main(void) {
pthread_t mythread;
int i;
if ( pthread_create( mythread, NULL, thread_function, NULL) ) {
printf(error creating thread.); bort();
}
for ( i=0; i20; i++) {
pthread_mutex_lock(mymutex); myglobal=myglobal+1; pthread_mutex_unlock(mymutex); printf(o);
fflush(stdout); sleep(1);
}
if ( pthread_join ( mythread, NULL ) ) {
printf(error joining thread.); abort();
}
printf(\nmyglobal equals %d\n,myglobal);
exit(0);
}
Comprehension time
If you compare this code to the version in my previous article, youll notice the addition of the calls pthread_mutex_lock() and pthread_mutex_unlock(). These calls perform a much-needed function in threaded programs. They provide a means of mutual exclusion (hence t
您可能关注的文档
- 11000地形测量技术设计.docx
- 20000字起笔部首检字表.docx
- 20148小继教培训心得体会.docx
- 20151人教版三年级数学上册教学工作总结.docx
- 20165理论题分析和总结.docx
- 20192广东公需课 中华传统美德.docx
- 22018年黄浦区中考物理二模卷含答案.docx
- 070602EditPlus安装步骤分析和总结.docx
- 100128万达国际时报文案.docx
- 100413晨报万达软文.docx
- 中国国家标准 GB/Z 37551.300-2026海洋能 波浪能、潮流能及其他水流能转换装置 第300部分:河流能转换装置发电性能评估.pdf
- GB/T 44937.3-2025集成电路 电磁发射测量 第3部分:辐射发射测量 表面扫描法.pdf
- 中国国家标准 GB/T 44937.3-2025集成电路 电磁发射测量 第3部分:辐射发射测量 表面扫描法.pdf
- 《GB/T 44937.3-2025集成电路 电磁发射测量 第3部分:辐射发射测量 表面扫描法》.pdf
- 中国国家标准 GB/T 44937.1-2025集成电路 电磁发射测量 第1部分:通用条件和定义.pdf
- GB/T 44937.1-2025集成电路 电磁发射测量 第1部分:通用条件和定义.pdf
- 《GB/T 44937.1-2025集成电路 电磁发射测量 第1部分:通用条件和定义》.pdf
- 中国国家标准 GB/T 4937.37-2025半导体器件 机械和气候试验方法 第37部分:采用加速度计的板级跌落试验方法.pdf
- 《GB/T 4937.10-2025半导体器件 机械和气候试验方法 第10部分:机械冲击 器件和组件》.pdf
- 中国国家标准 GB/T 44937.2-2025集成电路 电磁发射测量 第2部分:辐射发射测量TEM小室和宽带TEM小室法.pdf
原创力文档

文档评论(0)