多线程笔记

1. thread的创建

#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();
}

2.mutex的代码事例

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);

两种方式的参考:http://stackoverflow.com/questions/14320041/pthread-mutex-initializer-vs-pthread-mutex-init-mutex-param

3.Semaphores的代码事例

#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);

4.ConditionVariables的代码事例

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

其中OpenGLCCObjectautoreleasePool并不是线程安全的


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值