开发者

global struct and multiple threads in c

can someone explain me the compilation error in this code:

#include "common.h"

typedef struct nodeData {
    int procid;
    unsigned short localport;
    DWORD LIFETIME;
    DWORD HELLOTIMEOUT;
    DWORD MAXTIME;
} nodeData;

int listenerThread() {
    if(!bindSocket(listenSocket,nodeData.localport)){
        closesocket(listenSocket);
        WSACleanup();
        exit(-1);
}
    // more code goes here  
}

int main(int argc,char* argv[]) {
    nodeData.localport = 5001;
    // more code goes here  

}

I want the nodeData struct to be available to every listenerThread I will create. threads are going to manipulate this nodeData struct all the time (will protec开发者_如何学Pythont it with a mutex).

so i want this struct to be availabe globally. where do i initialize it ? my guess is in main.

the compilation error in the line

nodeData.localport = 5001;

is

error: a nonstatic member reference must be relative to a specific object

what am i'm missing here ?

thanks !


nodeData is a type not a variable - since you typedef it. Try e.g:

typedef struct nodeData_t {
    int procid;
    unsigned short localport;
    DWORD LIFETIME;
    DWORD HELLOTIMEOUT;
    DWORD MAXTIME;
} nodeData;

nodeData MyNodeData;

And then use the variable MyNodeData


Without going into why you shouldn't use a global for this, you haven't created a global variable anywhere, only defined a structure and typedef'd it.

Prior to main you would need to do:

nodeData myNodeData;

And access it as myNodeData

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜