日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

linux 線程同步實(shí)例

 Ethan的博客 2011-10-10
#include<stdio.h>

#include<unistd.h>
#include<stdlib.h>
#include<pthread.h>
#include<semaphore.h>

void *thread_function(void *arg);
pthread_mutex_t work_mutex;/*互斥量,保護(hù)工作區(qū)間及額外變量 time_to_exit*/

#define WORK_SIZE 1024
char work_area[WORK_SIZE];/*工作區(qū)*/
int time_to_exit=0;

int main()
{
    int res;
    pthread_t a_thread;
 void *thread_result;
 res = pthread_mutex_init(&work_mutex,NULL);//初始化工作區(qū)間
 if(res!=0){
  perror("Mutex initalization  failed");
  exit(EXIT_FAILURE);
 }
 res = pthread_create(&a_thread,NULL,thread_function,NULL);//創(chuàng)建新線程
 if(res!=0){
  perror("Thread creation failed");
  exit(EXIT_FAILURE);
 }

 /* 主線程*/
 pthread_mutex_lock(&work_mutex);
 printf("Input some text,Enter 'end' to finish\n");
 while(!time_to_exit){
  fgets(work_area,WORK_SIZE,stdin);
  pthread_mutex_unlock(&work_mutex);
  while(1){
   pthread_mutex_lock(&work_mutex);
   if(work_area[0]!='\0'){
    pthread_mutex_unlock(&work_mutex);
    sleep(1);
   }else{
    break;
   }
  }
 }

 pthread_mutex_unlock(&work_mutex);
 printf("\n Waiting for thread to finish...\n");
 res = pthread_join(a_thread,&thread_result);
 if(res !=0 ){
  perror("Thread joined\n");
  pthread_mutex_destroy(&work_mutex);
  exit(EXIT_SUCCESS);
 }
 printf("Thread joined\n");
 pthread_mutex_destroy(&work_mutex);
 exit(EXIT_SUCCESS);
}
 // 新線程
 void *thread_function(void *arg){

  sleep(1);
  pthread_mutex_lock(&work_mutex);
  while(strncmp("end",work_area,3)!=0){
   printf("You input %d characters\n",strlen(work_area)-1);
   work_area[0]='\0';
   pthread_mutex_unlock(&work_mutex);
   while(work_area[0]=='\0'){
    pthread_mutex_unlock(&work_mutex);
    sleep(1);
    pthread_mutex_lock(&work_mutex);
   }
  }
   time_to_exit=1;
   work_area[0]='\0';
   pthread_mutex_unlock(&work_mutex);
   pthread_exit(0);
 }

-----------------------------------------------------------------
編 譯運(yùn)行:
$gcc -Wall -lpthread -o test threadsyntest.c

$./test

結(jié) 果:

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購(gòu)買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類似文章 更多