0

I have a program that runs perfectly well when I have declare and initialize my List data structure at the top and then call my function generateID . It also works if I declare the List at the top and initialize the List inside the function. However the problem I am having is using threads to create the List. I keep getting segmentation errors.

At the top of my program, I have my declarations.

List* aLine;

At the bottom, I have two functions.

void CreateListA(int which)
{
   aLine = new List;
   currentThread->Yield();
}

void ThreadTest()
{
   Thread *gA = new Thread("Creates new List A");
   gA->Fork(CreateListA, 1);
   generateID();
}

Now, when I run thread test, I get segmentation errors. I am guessing that some where when creating the Lists with threads, memory got all messed up. But I can't figure out why there will be a problem with this? I created a player object the same way (with threads) and the program worked fine. Now I am trying to create the List data structure and it fails. ***Note generateID() uses append and remove to manipulate the list.

krikara
  • 2,395
  • 10
  • 37
  • 71

2 Answers2

2

After you Fork the new thread, generateID() is executed immediately: the thread may not have started yet or it could be in the middle of the creation of the list.

Maybe generateID() should be the function in the different thread and the creation of the list should be in the main one.

Paolo Brandoli
  • 4,681
  • 26
  • 38
  • This was the right idea. List wasn't ready by the time the function was called. Although I don't fully understand why the creation of the list wouldn't be finished before calling the function, this seems to be the case. Thank you – krikara Oct 14 '11 at 06:57
  • You don't have the control over the execution time of the new thread unless you use some synchronization method (for instance the system may start the new thread few seconds after you created it, and in the meantime it continues the execution of the main thread, that means that the instructions after fork() are executed before the new thread starts) – Paolo Brandoli Oct 14 '11 at 07:05
0

I suppose that Forkcreate a new thread, so, is possible that genereteID(), in the main thread, manipulate the list without been created yet. Try to invoke genereteID() in the thread, been sure of the list was really created. If not, check in genereteID() the correct creation and list initialization.

Tio Pepe
  • 3,071
  • 1
  • 17
  • 22
  • I can't use that test because I made a whole bunch of Lists and GenerateID manipulates all the lists at the same time. That is a possibility though, that the Lists weren't created correctly, but I still won't know how to fix it. – krikara Oct 14 '11 at 06:40
  • A simple way to test is adding a loop inside `genereteID()` waiting for list creation: something like `while (!aLine);`. Of course, initialize `aLine`to NULL at program begininig. – Tio Pepe Oct 14 '11 at 06:41