Multithreading 线程中的Rand()函数 #包括 #ifndef\uuu linux__ #include//以包含windows.h库// #恩迪夫 #包括 #包括 #定义NUM_线程5 #包括 void*PrintHello(void*threadid) { srand(时间(空)); 长tid,a; tid=(长)线程ID; a=rand()%5; printf(“你好,世界!是我,线程#%ld!%ld\n”,tid,a); pthread_exit(NULL); } int main(int argc,char*argv[]) { pthread_t threads[NUM_threads]; int rc; 长t,a; srand(时间(空)); 对于(t=0;t
请尝试从线程外部进行种子设定。问题是每个线程的种子都相同,谢谢。要解决此问题,我只需从线程中删除srand(time(NULL)),并且只在主线程中进行此操作…再次感谢相关:Multithreading 线程中的Rand()函数 #包括 #ifndef\uuu linux__ #include//以包含windows.h库// #恩迪夫 #包括 #包括 #定义NUM_线程5 #包括 void*PrintHello(void*threadid) { srand(时间(空)); 长tid,a; tid=(长)线程ID; a=rand()%5; printf(“你好,世界!是我,线程#%ld!%ld\n”,tid,a); pthread_exit(NULL); } int main(int argc,char*argv[]) { pthread_t threads[NUM_threads]; int rc; 长t,a; srand(时间(空)); 对于(t=0;t,multithreading,pthreads,srand,Multithreading,Pthreads,Srand,请尝试从线程外部进行种子设定。问题是每个线程的种子都相同,谢谢。要解决此问题,我只需从线程中删除srand(time(NULL)),并且只在主线程中进行此操作…再次感谢相关: #include <pthread.h> #ifndef __linux__ #include <windows.h>// to include the windows.h library// #endif #include <stdio.h> #include <stdlib.h
#include <pthread.h>
#ifndef __linux__
#include <windows.h>// to include the windows.h library//
#endif
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 5
#include <sys/timeb.h>
void *PrintHello(void *threadid)
{
srand(time(NULL));
long tid,a;
tid = (long)threadid;
a=rand()%5;
printf("Hello World! It's me, thread #%ld!%ld\n", tid,a);
pthread_exit(NULL);
}
int main (int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
int rc;
long t,a;
srand(time(NULL));
for(t=0; t<NUM_THREADS; t++){
a=rand()%5;
printf("In main: creating thread %ld,%ld\n", t,a);
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
/* Last thing that main() should do */
pthread_exit(NULL);
}