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

问题描述 投票:0回答:1

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

//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 argument
pthread_t sTcThread;
pthread_create(&sTcThread, NULL, server_to_client, (void*)whichOne);

这是线程实现

void* server_to_client(void* socket_desc)
{
    // make the argument 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);
    }
}

执行结果

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

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

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

将whichOne常量更改为1。

感谢答案和评论,解决了。

    int *whichOneImported = (int *) socket_desc;
    int whichOne = whichOneImported[0];
c multithreading
1个回答
3
投票

const int *whichOne = (int *) socket_desc;
确保
whichOne
不会被子例程的指令更改,但不会被另一个线程更改,因为它指向共享内存区域(在创建时将 address 传递给
whichOne
数组)你的线程,然后你修改它的值,当
flag == 1
)

你在另一个线程中设置了

whichOne[0] = 1;
,我不确定逻辑,但也许你的意思是:

whichOne[flag] = flag;

然后

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

分离数据

或者在运行线程之前创建

whichOne
的已分配副本。

© www.soinside.com 2019 - 2024. All rights reserved.