多线程

Thread safety

 A piece of code is thread-safe if it only manipulates shared data structures in a manner that guarantees safe execution by multiple threads at the same time. 



#include <pthread.h>
 
int increment_counter ()
{
        static int counter = 0;
        static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
 
        pthread_mutex_lock(&mutex);
 
        // only allow one thread to increment at a time
        ++counter;
        // store value before any other threads increment it further
        int result = counter;   
 
        pthread_mutex_unlock(&mutex);
 
        return result;
}

 

 

posted on 2013-12-13 06:03  brave_bo  阅读(172)  评论(0)    收藏  举报

导航