小编pow*_*e97的帖子

多线程c程序中的随机函数

请看整个问题

我知道srand()应该只调用一次,但我的第二个代码段表明这不能解决问题!

我写的程序给了我输出,我无法弄清楚为什么会这样.代码段的不同更改会产生不同的输出.

代码目的:
代码用于omp简单地为3个线程运行一段代码.每个线程必须使用该rand()函数打印3个随机值.因此,共有9项产出.线程0是主线程/主程序的运行流程.线程1和线程2是在线程代码开始时创建的新线程.
代码:

#include<omp.h>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>

int main()
{


     #pragma omp parallel num_threads(3)
    {
        srand(time(NULL));
        int i=0;
        for(i=0;i<3;i++)
        {
            printf("\nRandom number: %d by thread %d", rand(), omp_get_thread_num());
        }
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)


输出:

Random number: 17105 by thread 0
Random number: 30076 by thread 0
Random number: 21481 by thread 0
Random number: 17105 by thread 1
Random number: 30076 by thread 1
Random …
Run Code Online (Sandbox Code Playgroud)

c multithreading openmp

3
推荐指数
1
解决办法
4398
查看次数

标签 统计

c ×1

multithreading ×1

openmp ×1