I am writing a test program at this point to get a base down but when I run this it is feeding trash values into my struct.
If this is a bit incomplete I apologize, I’ve been working with this, searching the net for hours and everything I’m doing seems to be correct however I am getting garbage inserted into some critical values when I pass them through the pthread_create function.
Thanks for any help!
This code is giving me the following output:
main function running!
initial set of gWorkerid = 0
workerID = 319534848
Howdy Doody!
end sleep
gWorkerid is now trash value = -946297088
I am expecting:
main function running!
initial set of gWorkerid = 0
workerID = 0
Howdy Doody!
end sleep
gWorkerid is now trash value = 0
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <pthread.h>
#define MAX_CONN 3
#define MAX_LINE 1000
typedef struct worker_t
{
int id;
int connection;
pthread_t thread;
int used;
}WORKER_T;
struct sockaddr_in gServ_addr;
WORKER_T gWorker[MAX_CONN];
char sendBuff[1025];
// Thread function
void * worker_proc(void *arg)
{
WORKER_T *me = (WORKER_T*) arg;
printf("Howdy Doody!\n");
return NULL;
}
int main(int argc, char *argv[])
{
printf("main function running!\n");
pthread_t threadTest;
int i = 0;
gWorker[i].id = i;
printf("initial set of gWorkerid = %d\n", gWorker[i].id);
gWorker[i].connection = i;
gWorker[i].used = 1;
pthread_create(&gWorker[i], NULL, worker_proc, &gWorker[i]);
sleep(1);
printf("end sleep\n");
printf("gWorkerid is now trash value = %d\n", gWorker[i].id);
return 0;
}
The line:
should actually be:
That first parameter to
pthread_create()is where to store the thread ID and, in the case of your code, it stores it at the start of the structure, overwritingid.By passing the address of the thread ID part of the structure,
idshould be left untouched bypthread_create().