C - 本地线程变量是共享的

时间:2017-02-03 14:54:38

标签: c multithreading

我一直在尝试将变量传递给线程,但是创建第二个线程的瞬间,尽管它被创建为常量变量,但值仍会发生变化。

function main() {
  return Events({
    from_date: '2010-02-02',
    to_date:   '2017-02-03'
  }).reduce(mixpanel.reducer.count());
}

// 989322

这是线程的暗示

//for the first user
if (flag == 0) {
    //store the socket
    cl_sc[0] = client_sock_desc;
    //set id
    whichOne[0] = 0;
    puts("Client accepted");
    //second user ,same procedure
}
else if (flag == 1) {
    cl_sc[1] = client_sock_desc;
    whichOne[0] = 1;
    puts("Client accepted");
}

//create thread and pass cl_sc as arguement
pthread_t sTcThread;
pthread_create(&sTcThread, NULL, server_to_client, (void*)whichOne);

执行结果

  

客户接受Im 0加入我的套接字是4,我的朋友套接字是0
  客户接受Im 1加入我的套接字是5,我的朋友套接字是4

但是当线程0被激活时,就会发生这种情况

  

Im 1加入我的套接字是4,我的朋友套接字是4

将whichOne常量更改为1.

由于答案和评论而解决了这个问题。

void* server_to_client(void* socket_desc)
{
    //make the arguement readable
    const int* whichOne = (int*)socket_desc;
    //one int for retrieved data and one for his socket
    int retrieve, socket = cl_sc[whichOne[0]];
    //chat buddy socket
    int palsSocket;

    //the actual data
    char data[DATA_LENGTH];
    //free the string
    memset(data, 0, DATA_LENGTH);
    for (;;) {
        //set accordingly
        if (whichOne[0] == 0) {
            palsSocket = cl_sc[1];
        }
        else if (whichOne[0] == 1) {
            palsSocket = cl_sc[0];
        }
        printf("Im %d to join my socket is %d and my pals socket is %d\n", whichOne[0], socket, palsSocket);
    }
}

1 个答案:

答案 0 :(得分:3)

const int *whichOne = (int *) socket_desc;保证whichOne不会被子程序的指令改变,但不会被另一个线程更改,因为它指向共享内存区域(通过地址)创建线程时whichOne数组,然后在flag == 1)之后修改其值

你在另一个帖子中设置whichOne[0] = 1;,我不确定逻辑,但也许你的意思是:

whichOne[flag] = flag;

然后

pthread_create(&sTcThread, NULL, server_to_client, (void*) (whichOne+flag));

分隔数据

或者在运行主题之前制作whichOne的已分配副本。