linux中,C语言for语句中的随机数种子。

linux中,C语言for语句中的随机数种子。,第1张

#include<stdio.h>

#include<stdlib.h>

#include<time.h>

int main()

{

int i,j

srand(time(0))

for( i = 0i <1000i++)

for(j = 0i <100i++){

printf("%3d",rand()%100+1)

printf("\n")

}

return 0

}

#include "stdio.h"

#include "stdlib.h"

#include "time.h"/*需引用的头文件*/

int main(){

srand((unsigned)time(NULL))/*随机种子*/

int a=0,b=255//ASCII 字符范围

int i

for (i=0i<256i++){

int n=rand()%(b-a+1)+a/*n为a~b之间的随机数*/

printf("%c ",n)

}

return 0

}

配置文件为 conf.txt

测试代码如下,注意链接的时候加上 -lpthread 这个参数

#include <stdio.h>

#include <errno.h>//perror()

#include <pthread.h>

#include <unistd.h>//sleep()

#include <time.h>// time()

#include <stdlib.h>//rand()

#define FD "conf.txt"

typedef void *(*fun)(void *)

struct my_struct

{

unsigned time_to_wait

int n

}

void *test_thread(struct my_struct *)

int main (int argc, char const *argv[])

{

FILE *fp = fopen(FD, "r")

if (fp == NULL)

{

perror(FD)

return -1

}

srand((unsigned)time(NULL))//初始化随机种子

int thread_count

fscanf(fp, "%d", &thread_count)

fclose(fp)

if (thread_count <= 0)

{

printf("线程数<1,退出程序。\n")

return -1

}

pthread_t *ptid = (pthread_t *)malloc(sizeof(pthread_t) * thread_count) //保存线程ID

int i

for (i = 0i <thread_counti++)

{

int tw = rand() % thread_count + 1//随机等待时间

struct my_struct * p = (struct my_struct *)malloc(sizeof(struct my_struct))

if (p == NULL)

{

perror("内存分配错误")

goto ERROR

}

p->time_to_wait = tw

p->n = i + 1

int rval = pthread_create(ptid + i, NULL, (fun) test_thread, (void *)(p))//注意这里的强制转换(两个)

if (rval != 0)

{

perror("Thread creation failed")

goto ERROR

}

//sleep(1) //这句加也可以,不加也可以。最开始的时候加上这个是为了让两个线程启动的时候之间有一定的时间差

}

printf("主线程启动\n\n")

fflush(stdout)

for (i = 0i <thread_counti++)

{

pthread_join(*(ptid + i), NULL)//等待所有线程退出。

}

printf("\n主线程退出\n")

ERROR:

free(ptid)

return 0

}

void *test_thread(struct my_struct * p) //线程启动的时候运行的函数

{

printf("第%d个线程启动,预计运行%d秒\n", p->n, p->time_to_wait)

fflush(stdout)

sleep(p->time_to_wait) //让线程等待一段时间

printf("第%d个线程结束\n", p->n)

fflush(stdout)

free(p)

return NULL

}

你的第二个问题我在百度HI回你了~


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/7516898.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-06
下一篇 2023-04-06

发表评论

登录后才能评论

评论列表(0条)

保存