使用 Pthread
1)phtead_create
/* Create a new thread, starting with execution of START-ROUTINEgetting passed ARG. Creation attributed come from ATTR. The newhandle is stored in *NEWTHREAD. */extern int pthread_create (pthread_t *__restrict __newthread,const pthread_attr_t *__restrict __attr,void *(*__start_routine) (void *),void *__restrict __arg) __THROWNL __nonnull ((1, 3));
pthread_create(&thread_handle[thread],NULL,thread_sum,(void*)thread);
- pthread_t 的存储位置
- pthread 指针位置
- 创建的线程函数
-
互斥锁
1) 使用mutex加锁
信号量 pthread_mutex_t
- 加锁 pthread_mutex_lock(&mutex)
- 解锁 pthread_mutex_unlock(&mutex)
```cpp
include
pthread_mutex_t mutex; //信号量
void thread0(){ pthread_mutex_lock(&mutex); / shared area / pthread_mutex_unlock(&mutex); // … }
int main(){ pthread_mutex_init(&mutex,NULL); // … pthread_mutex_destroy(&mutex); }
<a name="I7Cuj"></a>#### 2) 使用semaphore加锁```cpp#include<pthread.h>#include<semaphore.h>sem_t semaphore_p; // 信号量void thread0(){sem_post(&semaphore_p);/* shared area */sem_wait(&semaphore_p);// ...}int main(){sem_init(&semaphore_p, 0, 0);// ...sem_destroy(&semaphore_p);}
使用 boost
#include <boost/thread.hpp>std::shared_ptr<boost::thread> thread0_ptr;void thread0(int param){/* code */}int main(){int param = 10;thread0_ptr.reset(new boost::thread(boost::bind(&)));return 0;}
