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分 编辑过]
|