使用 Pthread

1)phtead_create

  1. /* Create a new thread, starting with execution of START-ROUTINE
  2. getting passed ARG. Creation attributed come from ATTR. The new
  3. handle is stored in *NEWTHREAD. */
  4. extern int pthread_create (pthread_t *__restrict __newthread,
  5. const pthread_attr_t *__restrict __attr,
  6. void *(*__start_routine) (void *),
  7. void *__restrict __arg) __THROWNL __nonnull ((1, 3));
  1. 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); }

  1. <a name="I7Cuj"></a>
  2. #### 2) 使用semaphore加锁
  3. ```cpp
  4. #include<pthread.h>
  5. #include<semaphore.h>
  6. sem_t semaphore_p; // 信号量
  7. void thread0(){
  8. sem_post(&semaphore_p);
  9. /* shared area */
  10. sem_wait(&semaphore_p);
  11. // ...
  12. }
  13. int main(){
  14. sem_init(&semaphore_p, 0, 0);
  15. // ...
  16. sem_destroy(&semaphore_p);
  17. }

使用 boost

  1. #include <boost/thread.hpp>
  2. std::shared_ptr<boost::thread> thread0_ptr;
  3. void thread0(int param){
  4. /* code */
  5. }
  6. int main(){
  7. int param = 10;
  8. thread0_ptr.reset(new boost::thread(boost::bind(&)));
  9. return 0;
  10. }

chrono 的使用