推 GiPaPa:感謝 我再研究一下<(_ _)>140.113.140.159 03/14 13:07
如果不用glibc的rand...
那...就把他的公式抄過來就好...
http://www.cs.ccu.edu.tw/~ksc91u/rand/rand_pthread.c
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
void * msrand(void * data);
int my_rand_r (unsigned int *seed);
struct p{
int * data;
int id;
};
int main(){
pthread_t pt[5];
struct p pp[5];
int d[5]={7919,22307,48611,104729,287117};
for(int i=0;i<5;i++){
pp[i].data=&d[0];
pp[i].id=i;
pthread_create(&pt[i],NULL,msrand,&pp[i]);
}
for(int i=0;i<5;i++){
pthread_join(pt[i],NULL);
}
printf("%d %d %d %d %d\n",d[0],d[1],d[2],d[3],d[4]);
}
static unsigned int seed;
int my_srand(unsigned int s){
seed=s;
}
unsigned int my_rand(){
// seed=my_rand_r(&seed);
// return seed;
return my_rand_r(&seed);
}
int
my_rand_r (unsigned int *seed)
{
unsigned int next = *seed;
int result;
next *= 1103515245;
next += 12345;
result = (unsigned int) (next / 65536) % 2048;
next *= 1103515245;
next += 12345;
result <<= 10;
result ^= (unsigned int) (next / 65536) % 1024;
next *= 1103515245;
next += 12345;
result <<= 10;
result ^= (unsigned int) (next / 65536) % 1024;
*seed = next;
return result;
}
void * msrand(void * data){
struct p * pp = (struct p *) data;
int * ptr=pp->data;
int self=pp->id;
my_srand(ptr[(self+1)%5]);
for(int i=0;i<100;i++){
ptr[self]^=my_rand();
ptr[self]<<13;
usleep(1);
sched_yield();
}
}
其實也可以不用pthread...
用alarm..來模擬thread的效果..
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.123.102.254