论坛: 编程破解 标题: 线程 复制本贴地址    
作者: SysHu0teR [syshunter]    版主   登录
piglet写的测试pthread代码,做为入门教程不错,加上注释给新手学学
代码:

//gcc -D_REENTRANT -I/usr/include/nptl -L/usr/lib/nptl -lpthread filename.c -o filename

#include <stdio.h>
//  #include <string.h>
// #include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>


void *thread_function(void *arg);
sem_t bin_sem;                            //定义信号量,作用和PV原语类似

#define WORK_SIZE 1024
char work_are[WORK_SIZE];

int main(){
  int res;
  pthread_t a_thread;                                //定义线程标识符,后面要用
  void *thread_result;

  res=sem_init(&bin_sem,0,0);                        //初始化信号量
  if(res!= 0){
    perror("Semaphore initialization failed");
    exit(EXIT_FAILURE);
  }
  res=pthread_create(&a_thread,NULL,thread_function,NULL);          //创建线程
  if(res!=0){
    perror("Thread creation failed");
    exit(EXIT_FAILURE);
  }
  printf("Input some text. Enter 'end' to finish\n");
  while(strncmp("end",work_are,3)!=0){
    fgets(work_are,WORK_SIZE,stdin);
    sem_post(&bin_sem);                  //当用户输入一行后,让信号灯加1以激活thread_function()
  }

  printf("\n Waiting for thread to finish... \n");
  res=pthread_join(a_thread,&thread_result);        //等待a_thread指定的线程结束.
  if(res!=0){
    perror("Thread join failed");
    exit(EXIT_FAILURE);
  }

  printf("Thread joined\n");
  //
  sem_destroy(&bin_sem);                                  //销毁信号量
  exit(EXIT_SUCCESS);
}

void *thread_function(void *arg){
  //check if start or not
  sem_wait(&bin_sem);                      //等待,如果信号量大于0,就减1然后继续执行
  //work for character count until type 'end'
  while(strncmp("end",work_are,3)!=0){
    //processing
    printf("You input %d characters\n",strlen(work_are) -1);
    //stop processing
  sem_wait(&bin_sem);
  }
  pthread_exit(NULL);                             
}



FREEBSD下编译:
gcc -pthread test_pthread.c -o test_pthread



[此贴被 SysHu0teR(syshunter) 在 09月05日14时01分 编辑过]

地主 发表时间: 04-09-05 13:59

回复: hackerjune [hackerjune]   论坛用户   登录
收了,但是还是不怎么明白啊

B1层 发表时间: 04-09-05 19:35

回复: lqfrla [lqfrla]   论坛用户   登录
鄙视楼主

不经过我姐姐的同意就发人家的程序帖上来,

鄙视你

B2层 发表时间: 04-09-05 21:45

论坛: 编程破解

20CN网络安全小组版权所有
Copyright © 2000-2010 20CN Security Group. All Rights Reserved.
论坛程序编写:NetDemon

粤ICP备05087286号