#include <pthread.h> void* thread_function(void *arg) { .... return NULL; } pthread_t mythread; if ( pthread_create( &mythread, NULL, thread_function, NULL/*args*/) ) { printf("error creating thread."); abort(); }
pthread_mutex_t mymutex=PTHREAD_MUTEX_INITIALIZER; pthread_mutex_lock(&mymutex); //.... pthread_mutex_unlock(&mymutex);
pthread_mutex_t mutex; if(pthread_mutex_init(&mutex, NULL)) { printf("Unable to initialize a mutex\n"); return -1; } pthread_mutex_lock(&mymutex); //.... pthread_mutex_unlock(&mymutex); // Clean up the mutex pthread_mutex_destroy(&mutex);
#include <semaphore.h> #include <pthread.h> sem_t OKToBuyMilk; if(sem_init(&OKToBuyMilk, 0, 1)) { printf("Could not initialize a semaphore\n"); return -1; } sem_wait(&OKToBuyMilk); //.... sem_post(&OKToBuyMilk); sem_destroy(&OKToBuyMilk);
pthread_cond_t count_threshold_cv; pthread_cond_init (&count_threshold_cv, NULL); // one thread pthread_mutex_lock(&count_mutex); if (count == COUNT_LIMIT) { pthread_cond_signal(&count_threshold_cv); } pthread_mutex_unlock(&count_mutex); // -other thread pthread_mutex_lock(&count_mutex); while (count<COUNT_LIMIT) { pthread_cond_wait(&count_threshold_cv, &count_mutex); } pthread_mutex_unlock(&count_mutex); pthread_cond_destroy(&count_threshold_cv);
相关书籍《POSIX Multiple Thread Programming Primer》
用man可以查看相关函数的说明。比如:man pthread_create
https://computing.llnl.gov/tutorials/pthreads/
http://mij.oltrelinux.com/devel/unixprg/#threads
http://pages.cs.wisc.edu/~travitch/pthreads_primer.html
http://www.tutorialspoint.com/cplusplus/cpp_multithreading.htm
关于在cocos2dx中使用多线程的注意点,请参考http://www.cocos2d-x.org/projects/cocos2d-x/wiki/How_to_use_pthread#How-to-use-pthread;
其中OpenGL,CCObject的autoreleasePool并不是线程安全的