【问题标题】:How to pass an element from a array of strings to a thread?如何将字符串数组中的元素传递给线程?
【发布时间】:2014-02-08 16:09:38
【问题描述】:

在解决“将元素从字符串数组传递到线程”的问题时需要一些帮助。我的代码在此文本之后。我在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);
}

我的输出是:

 My name is Agent � @

 My name is Agent � @

 My name is Agent � @

【问题讨论】:

  • void * 之间有太多多余的演员表。此外,字符串文字应声明为const char *,而不是char *

标签: c arrays string multithreading


【解决方案1】:

试试这个:

pthread_create(&agent_t[i], 0, agent, agent_colour[i]); 

【讨论】:

    【解决方案2】:

    pthread_create 调用中这是错误的

    &agent_colour[i]
    

    你只是想传递字符串

    agent_colour[i]
    

    【讨论】:

      【解决方案3】:

      agent_colour 是一个指针数组。所以只需在 pthread create 中像这个 agent_colour[i] 一样传递。

      【讨论】:

        猜你喜欢
        • 2017-03-04
        • 1970-01-01
        • 2016-10-25
        • 2023-02-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多