linux深入

Lecture 3 (6D-8A): 共享内存编程--Pthre

2020-11-08  本文已影响0人  Catherin_gao

一. 共享内存编程

1. 多线程容易遇到的问题

2. 多线程可以通过哪些方式实现:

3. Process和thread的区别

pthread_creat(&thread1,NULL,func1,&arg);
pthread_join(thread1,*status);
func(&arg){
.
.
.
return(*status)
}

二. Pthread

4. pthread的例子

#include <pthread.h>
#include <stdio.h>
#define NUM_THREADS 5

void *PrintHello(void *threadld){
  long* data = static_cast<long*> threadld;
  printf("Hello World! thread #%ld!\n", *data);
  pthread_exit(NULL);
}

int main(int argc, char *argv[]){
  pthread_t threads[NUM_THREADS];
  for(long tid=0;tid<NUM_THREADS;tid++){
       pthread_create(&threads[tid],NULL,PrintHello,(void*)&tid);
  }
  pthread_exit(NULL);
}

5. Pthread Joining & Detaching

6. 同步问题

producer: move ax, counter      -> ax=5
producer: add ax, 1                   -> ax=6
context switch
consumer: move bx, counter     ->bx =5
consumer: sub bx, 1                  ->bx =4
context switch
producer: move counter, ax       -> counter =6
context switch
consumer: move counter, bx     ->counter =4

6.1 Pthread

while (lock == 1); lock = 1;
.
critical section
. lock = 0;
/* no operation in while loop */ /* enter critical section */
/* leave critical section */

Pthread Lock/ Mutex Routines

#include "pthread.h"
pthraed_mutex_t mutex;        
pthread_mutex_init(&mutex, NULL);
pthread_mutex_lock(&mutex); 
        Critical Section
pthread_mutex_unlock(&mutex);
pthread_mutex_detroy(&mutex);

Bounded-buffer Problem

Condition Variable (CV)

上一篇下一篇

猜你喜欢

热点阅读