线程程序和结构将值更改为垃圾

时间:2013-02-01 03:48:43

标签: c multithreading struct return-value

我现在正在编写一个测试程序以获得基础,但是当我运行它时,它会将垃圾值提供给我的结构。

如果这有点不完整我道歉,我一直在努力,在网上搜索几个小时,我正在做的一切似乎都是正确的但是当我通过它时,我将垃圾插入一些关键值pthread_create函数。

感谢您的帮助!

此代码给出了以下输出:

主要功能正在运行!

gWorkerid的初始设置= 0

workerID = 319534848

Howdy Doody!

结束睡眠

gWorkerid现在是垃圾值= -946297088

我期待:

主要功能正在运行!

gWorkerid的初始设置= 0

workerID = 0

Howdy Doody!

结束睡眠

gWorkerid现在是垃圾值= 0

    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <arpa/inet.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <sys/types.h>
    #include <pthread.h>

    #define MAX_CONN 3
    #define MAX_LINE 1000

    typedef struct worker_t
    {
        int id;
        int connection;
        pthread_t thread;
        int used;
    }WORKER_T;

    struct sockaddr_in gServ_addr;

    WORKER_T gWorker[MAX_CONN];
    char sendBuff[1025];

    // Thread function
    void * worker_proc(void *arg)
    {
        WORKER_T *me = (WORKER_T*) arg;

        printf("Howdy Doody!\n");

        return NULL;
    }

    int main(int argc, char *argv[])
    {
        printf("main function running!\n");
        pthread_t threadTest;
        int i = 0;

        gWorker[i].id = i;
        printf("initial set of gWorkerid = %d\n", gWorker[i].id);
        gWorker[i].connection = i;
        gWorker[i].used = 1;
        pthread_create(&gWorker[i], NULL, worker_proc, &gWorker[i]);

        sleep(1);

        printf("end sleep\n");
        printf("gWorkerid is now trash value = %d\n", gWorker[i].id);

        return 0;
    }

2 个答案:

答案 0 :(得分:0)

该行:

pthread_create (&gWorker[i], NULL, worker_proc, &gWorker[i]);

实际应该是:

pthread_create (&(gWorker[i].thread), NULL, worker_proc, &gWorker[i]);

pthread_create()的第一个参数是存储线程ID的位置,对于代码,它将它存储在结构的开头,覆盖id

通过传递结构的线程ID部分的地址,id应保持pthread_create()不受影响。

答案 1 :(得分:0)

尝试更改:


pthread_create(&gWorker[i], NULL, worker_proc, &gWorker[i]);

为:


pthread_create(&(gWorker[i].thread), NULL, worker_proc, &gWorker[i]);

pthread_create()期望指向pthread_t的指针作为第一个参数,然后填充它。在您的情况下,pthread_create填充在WORKER_T结构的顶部。