首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在C++中使用线程和数组

如何在C++中使用线程和数组
EN

Stack Overflow用户
提问于 2011-03-16 19:09:08
回答 3查看 13.9K关注 0票数 1

问题是:编写全局整数大小为N的一维数组A的程序的因子M。使用线程,主线程用随机整数初始化A和M,创建N个线程,使得第i个线程找到Ai =M* Ai,最后打印数组A。

我的问题是,我有一个数组初始化的错误,我也不确定以正确的方式制作线程。我希望我已经把我的问题解释清楚了。

代码语言:javascript
运行
复制
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int M;
int [10] A;

void *run(void *t)
{
   A[(int)t]=A[(int)t]*M;
   pthread_exit(NULL);
}


int main()
{
   pthread_t [10] th;
   srand(time(0))%20;
   M=rand();
   int t;
   for(t = 0; t < 10; t++)
   {
     pthread_create(&th[t], NULL, run, (void *)t);
   }

   int j;
   for(j=0;j<10;j++)
    A[j]=j;

   int i;
   for(i = 0; i < 10; i++)
   {
     pthread_join(th[i], NULL);
     printf("%d:  %d\n", i,A[i]);
   }

   printf("Thread main\n");
   pthread_exit(NULL);
}

以下是错误:

代码语言:javascript
运行
复制
que1.c:5: error: expected identifier or ‘(’ before ‘[’ token
que1.c: In function ‘run’:
que1.c:9: error: ‘A’ undeclared (first use in this function)
que1.c:9: error: (Each undeclared identifier is reported only once
que1.c:9: error: for each function it appears in.)
que1.c: In function ‘main’:
que1.c:16: error: expected identifier or ‘(’ before ‘[’ token
que1.c:17: error: void value not ignored as it ought to be
que1.c:22: error: ‘th’ undeclared (first use in this function)
que1.c:27: error: ‘A’ undeclared (first use in this function)
EN

Stack Overflow用户

发布于 2011-03-16 19:21:04

除了@Oli Charlesworth的回答之外,srand不返回任何值,它被声明为void,所以您不能编写srand(time(0)) % 20

票数 2
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5324432

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档