Reputation: 31
I'm looking on how to use threads in C language. I found how to use it on windows but I don't know why it just doesn't work on my computer as it should ...
First thing: I know that I have to create a struct to use parameters, so here's my struct:
typedef struct monclient
{
SOCKADDR_IN _csin;
char _ip[30];
int _port;
char _name[255];
int _taille;
monclient* _next;
int _justconnected;
}client;
My header.h file:
#pragma once
#include<stdio.h>
#include<winsock2.h>
#include <windows.h>
#include "Structures.h"
#pragma warning (disable:4996)
#pragma comment(lib,"ws2_32.lib") //Winsock Library
DWORD WINAPI ThreadProc(LPVOID lpParameter); //Prototype to be used everywhere in code
Here's what you need to know about my main():
void main()
{
client* mesclients = (client*)malloc(sizeof(client));
//I'm filling informations ...
thread = CreateThread(NULL, 0, ThreadProc, &mesclients, 0, NULL);
if(thread)
{printf("success\n");
}
else
{
printf("problem\n");
}
}
and now most important: my thread
#include "Header.h"
DWORD WINAPI ThreadProc(LPVOID lpParameter)
{
client* test = (client*)lpParameter;
printf("%s", test->_name);
// I CANT RETURN THE NAME ... ALL THE VALUES ARE RANDOM IT SEEMS LIKE HE CANT ACCESS THE ORIGINAL POINTER
return 0;
}
If someone could explain what is going wrong here it would be awesome ! I think I sent the adress of my pointer so it becomes a pointer of pointer but I'm not sure about it... Maybe it's just a reference here. Thanks for further help.
Impact
Upvotes: 0
Views: 315
Reputation: 14491
The code send the address of the mesclients to the thread, which is a variable on the main stack. You want to send the address of the client
object that was malloc-ed.
thread = CreateThread(NULL, 0, ThreadProc, mesclients, 0, NULL);
Upvotes: 1