如何从字符串数组一个线程传递一个元素? [英] How to pass an element from a array of strings to a thread?
本文介绍了如何从字符串数组一个线程传递一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
需要解决从字符串数组一个线程传递一个元素的问题,一些援助。我的code是该文本之后。我宣布串在数组主
函数,然后通过数组的一个元素,一个线程。在线程我强制转换回的char *类型,然后再打印,但打印不需要的值。将是解决感激:
的#include<&stdio.h中GT;
#包括LT&;&pthreads.h中GT;void *的代理(无效*);INT主(INT ARGC,CHAR *的argv []){
INT I;
的pthread_t agent_t [3];
字符* agent_colour [3] = {红,白,布朗}; 对于(I = 0; I&下; = 2;我++){
在pthread_create(安培; agent_t [I],0,代理,和放大器; agent_colour [I]);
} 对于(I = 0; I&下; = 2;我++){
在pthread_join(agent_t [I],NULL);
} 返回0;
}void *的代理(无效* ARG){
字符*色=(字符*)ARG;
INT X;
函数srand(时间(NULL));
X =兰特()%5 + 1;
睡眠(X);
的printf(\\ n我的名字是代理%S \\ n,颜色);
了pthread_exit(NULL);
}
我的输出是:
我的名字是代理@ 我的名字是代理@ 我的名字是代理@
解决方案
试试这个:
在pthread_create(安培; agent_t [I],0,代理,agent_colour [I]);
Needed some assistance in solving a problem of "passing an element from a array of strings to a thread". My code is after this text. I declared an array of strings in the main
function and then passed one element of the array to a thread. In the thread I typecast it back to char* type and then print, but it prints garbage values. Would be grateful for the solution:
#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);
}
My output is:
My name is Agent � @
My name is Agent � @
My name is Agent � @
解决方案
Try this:
pthread_create(&agent_t[i], 0, agent, agent_colour[i]);
这篇关于如何从字符串数组一个线程传递一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文