Abu*_*que 2 c arrays string multithreading
需要一些帮助来解决"将元素从一个字符串数组传递给一个线程"的问题.我的代码是在这个文本之后.我在main函数中声明了一个字符串数组,然后将一个数组元素传递给一个线程.在线程中我将它转换回char*类型然后打印,但它会打印垃圾值.将不胜感激解决方案:
#include <stdio.h>
#include <pthread.h>
void *agent(void *);
int main(int argc, char *argv[]) {
int i;
pthread_t agent_t[3];
char *agent_colour[3] = {"Red","White","Brown"};
for(i = 0 ; i <= 2 ; i++) {
pthread_create(&agent_t[i], 0, agent, &agent_colour[i]);
}
for(i = 0 ; i <= 2 ; i++) {
pthread_join(agent_t[i], NULL);
}
return 0;
}
void *agent(void *arg) {
char *colour = (char*)arg;
int x;
srand(time(NULL));
x = rand() % 5 + 1;
sleep(x);
printf("\n My name is Agent %s\n", colour);
pthread_exit(NULL);
}
Run Code Online (Sandbox Code Playgroud)
我的输出是:
My name is Agent ? @
My name is Agent ? @
My name is Agent ? @
Run Code Online (Sandbox Code Playgroud)
试试这个:
pthread_create(&agent_t[i], 0, agent, agent_colour[i]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1098 次 |
| 最近记录: |