static int a[10000]; static sum1,sum2,sum, p;
pthread_mutex_t mutex; //互斥量,用于共享变量访问
void *thread1(void *arg) {
int i; sum2=0; for(; ;) {
pthread_mutex_lock (&mutex); if (p<10000) { sum2=sum2+a[p]; usleep(1); p++;
pthread_mutex_unlock(&mutex); }
else {
pthread_mutex_unlock(&mutex); break; }
}
pthread_exit((void*) sum2); }
int main(int argc,char* argv[]) {
pthread_t tidp; int error,i; int res;
int thread_result;
pthread_mutex_init (&mutex,NULL); //线程互斥量初始化为 p=0;
for (i=0; i<10000; i++) a[i]=i;
error = pthread_create(&tidp,NULL, thread1,NULL); if(error != 0) {
printf(\"thread is not created...\\n\"); return -1; }
sum1=0;
for(; ;) {
pthread_mutex_lock (&mutex); if (p<10000) { sum1=sum1+a[p]; usleep(1); p++;
pthread_mutex_unlock(&mutex); }
else {
pthread_mutex_unlock(&mutex); break; } }
pthread_join(tidp,&thread_result); sum=sum1+sum2;
printf(\"the sum of array[10000] is %d\\n\
printf(\"the part sum of thread1 get is %d\\n\
return 0; }
$ gcc lin-thread-4.c -lpthread -o lin-thread-4
$ ./lin-thread-4
2. 分析、调试和执行一个多线程示例程序lin-thread-5.c
该程序创建两个线程,一个线程负责读入键盘输入的文本,另一个线程负责统计和显示输入的字符个数,文本输入以“end”表示输入结束。程序在主线程中对结束的两个线程进行归并。
lin-thread-5.c
#include #include #include #include #include #include void *input_text(void *arg); void *count_text(void *arg); void *stat_text(void *arg);
sem_t bin_sem; //信号量,用于线程同步 #define WORK_SIZE 1024 char work_area[WORK_SIZE]; int main() {
int res; //线程函数执行的返回值
pthread_t input_thread,stat_thread; //线程标识符变量 void *thread_result; //线程执行的返回值
res = sem_init(&bin_sem,0,0); //线程同步信号量初始化为0
if (res!=0) {
perror(\"Semaphore init failed\"); exit(EXIT_FAILURE); }
res = pthread_create(&input_thread,NULL, input_text,NULL); if (res!=0) {
perror(\"Input Thread init failed\"); exit(EXIT_FAILURE); }
res = pthread_create(&stat_thread,NULL, stat_text,NULL); if (res!=0) {
perror(\"Stat Thread init failed\"); exit(EXIT_FAILURE); }
printf(\"Waiting for thread to finish…\\n\");
res = pthread_join(input_thread,&thread_result); res = pthread_join(stat_thread,&thread_result); printf(\"Threads joined\\n\"); sem_destroy(&bin_sem); exit(EXIT_SUCCESS); }
void *input_text(void *arg) {
printf(\"Input some text. Enter ‘end’ to finish\\n\"); while(strncmp(\"end\ fgets(work_area,WORK_SIZE,stdin);
sem_post(&bin_sem); /* 产生事件 */ }
pthread_exit(0); }
void *stat_text(void *arg) {
sem_wait(&bin_sem); /* 等待事件 */ while(strncmp(\"end\
printf(\"You input %d characters\\n\ sem_wait(&bin_sem); }
pthread_exit(NULL); }
$ gcc -D_REENTRANT lin-thread-5.c -o lin-thread-5 -lpthread $ ./lin-thread-5