不保留其线程值全局变量 [英] global variable not retaining its value in thread

查看:146
本文介绍了不保留其线程值全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个多线程的服务器,它拥有一个全球性的指针链表,在线程我试图插入一些数据,但不保留数据(我插),是可能在线程全球价值不保留。我使用下面的code(这是一个简单的版本。)

 结构节点{
  INT CN; //  结构节点*接下来的;
};
/ * GLOBAL变量* /
结构节点*启动; //全球指针链表
/* 结束 */INT主(INT ARGC,CHAR *的argv []){    启动=(结构节点*)malloc的(的sizeof(结构节点));
    启动 - > CN = 0;    INT PID;
    / *服务器的宣言到这里* /
    的printf(服务器正在运行... \\ n);
    而(1){        / *接受插座* /        PID =叉();
        如果(PID℃,)
            错误(叉ERROR);
        如果(PID == 0){
            关闭(ServerSocket的);
            dostuff(childSocket,启动);
            出口(0);
        }
        其他
            关闭(childSocket);    }
    返回0;
}无效dostuff(INT袜子,结构节点*指针){    returnStatus =读(袜子,和放大器; requestToJoin,sizeof的(INT));
    如果(returnStatus℃,)
        错误(ERROR从套接字读取);
    其他{
        / *插入数据对全球指针* /
    }}


解决方案

这是一个多进程的服务器不是多线程,全局数据不会父母和孩子之间共享流程它就会在某一点重复,你应该看看共享内存如果你想共享多个进程或之间的数据< A HREF =htt​​ps://computing.llnl.gov/tutorials/pthreads/相对=nofollow>如果你想使用线程(其中共享他们的父母的记忆)的pthreads 的。如果你的编译器支持 C11 你也可以使用&LT; threads.h&GT;

I made a multi threaded server, it has a global pointer to a linked list, in thread I am trying to insert some data, but that data (which I insert) not retaining, is that possible that in threads that global value is not retaining. I am using the following code (it's a simplest version.)

struct node {
  int cn; //

  struct node *next;
};




/*GLOBAL VARIABLES*/
struct node *start; //Global pointer to Linked List
/* END */

int main(int argc, char *argv[]) {

    start = (struct node *)malloc(sizeof(struct node));
    start -> cn =0;

    int pid;
    /* Declaration of Server goes here */
    printf("Server Running ...\n");
    while (1) {

        /* accepting socket*/

        pid = fork();
        if (pid < 0)
            error("ERROR on fork");
        if (pid == 0)  {
            close(serverSocket);
            dostuff(childSocket,start);
            exit(0);
        }
        else
            close(childSocket);

    }
    return 0;
}

void dostuff (int sock, struct node *pointer){

    returnStatus = read(sock, &requestToJoin, sizeof(int));
    if (returnStatus < 0) 
        error("ERROR reading from socket");
    else{
        /* Insert Data to global Pointer */
    }

}

解决方案

That's a multi-process server not multi-threaded, global data is not shared between parent and child processes it gets duplicated at a certain point, you should look into shared memory if you want to share data between multiple processes or pthreads if you want to use threads (which share their parent's memory). If your compiler supports C11 you could also use <threads.h>

这篇关于不保留其线程值全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆