POSI threads eplained part 2分析和总结分析和总结.docxVIP

  • 0
  • 0
  • 约1.84万字
  • 约 12页
  • 2023-04-25 发布于上海
  • 举报

POSI threads eplained part 2分析和总结分析和总结.docx

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

您可能关注的文档

文档评论(0)

1亿VIP精品文档

相关文档