LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 732|回复: 4

各位高手大哥帮帮忙啊!!

[复制链接]
发表于 2004-6-1 12:04:03 | 显示全部楼层 |阅读模式
我昨天发的那个帖子的程序问题,请各位高手多多帮忙啊,我现在急需要啊!!多谢了!线程函数请各位多指教啊。如果谁有现成的关于读写者问题的或是五个哲学家问题的请告诉一下小弟,多谢了!!
发表于 2004-6-6 08:25:55 | 显示全部楼层
线程创建
#include <pthread.h>
#include <stdio.h>
/*Prints x ’s to stderr.The parameter is unused.Does not return.*/
void*print_xs (void*unused){
while (1)
fputc (‘x ’,stderr);
return NULL;
}
/*The main program.*/
int main (){
pthread_t thread_id;
/*Create a new thread.The new thread will run the print_xs
function.*/
pthread_create (&thread_id,NULL,&print_xs,NULL);
/*Print o ’s continuously to stderr.*/
while (1)
        fputc (‘o ’,stderr);
return 0;
}
发表于 2004-6-6 08:27:30 | 显示全部楼层
/*
* Join thread
*/
int main (){
pthread_t thread1_id;
pthread_t thread2_id;
struct char_print_parms thread1_args;
struct char_print_parms thread2_args;
thread1_args.character =’x ’;
thread1_args.count =30000;
pthread_create (&thread1_id,NULL,&char_print,&thread1_args);
/*Create a new thread to print 20,000 o ’s.*/
thread2_args.character =’o ’;
thread2_args.count =20000;
pthread_create (&thread2_id,NULL,&char_print,&thread2_args);
/*Make sure the first thread has finished.*/
pthread_join (thread1_id,NULL);
/*Make sure the second thread has finished.*/
pthread_join (thread2_id,NULL);
/*Now we can safely return.*/
return 0;
}
发表于 2004-6-6 08:30:34 | 显示全部楼层
/*
* Get result
*/
#include <pthread.h>
#include <stdio.h>
/*Compute successive prime numbers (very inefficiently).Return the
Nth prime number,where N is the value pointed to by *ARG.*/
void*compute_prime (void*arg)
{
int candidate =2;
int n =*((int*)arg);
while (1){
        int factor;
        int is_prime =1;
/*Test primality by successive division.*/
        for (factor =2;factor <candidate;++factor)
        if (candidate %factor ==0){
               is_prime =0;
               break;
               }
/*Is this the prime number we ’re looking for?*/
        if (is_prime){
               if (--n ==0)
/*Return the desired prime number as the thread return value.*/
                     return (void*)candidate;
               }
        ++candidate;
        }
return NULL;
}
int main ()
{
pthread_t thread;
int which_prime =5000;
int prime;
/*Start the computing thread,up to the 5,000th prime number.*/
pthread_create (&thread,NULL,&compute_prime,&which_prime);
/*Do some other work here...*/
/*Wait for the prime number thread to complete,and get the result.*/
pthread_join (thread,(void*)&prime);
/*Print the largest prime it computed.*/
printf(“The %dth prime number is %d.\n ”,which_prime,prime);
return 0;
}
发表于 2004-6-6 08:31:26 | 显示全部楼层
还有很多了,随便找本书看看就好了
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表