Question

I had old network client program. I am trying to change it to multithreaded program.

Could you please tell me your opinion about thread-safety of the following JobList?

Original process (thread1)

//Initializing
bThread1Done = false;
bThread2Done = true

While (true)
{
…
If (bThread2Done) {
  bThread2Done = false;
  while (!JobList.empty())
  {
    JobList.pop_front();
    LocalJobList.push_back();
  }
  bThread1Done = true;
}
…
Process(LocalJobList);
}

New background thread (thread 2)

While (true)
{
…
Recv(sock);
If (bThread1Done) {
  bThread1Done = false;
  while (!RecvList.empty())
  {
    RecvList.pop_front();
    JobList.push_back();
  }
  bThread2Done = true;
}
}
Was it helpful?

Solution 2

Your code is not thread safe....

Protect your shared structures with mutexes and semaphores so only one process will access it at any given time.

Additional information Your code thread safety is dependent on the compilers implementation of assignments like bThread2Done = true; and test like if (bThread2Done) {... which depending on

  1. the CPU architecture and
  2. the compiler optimization

may or may not happen atomically -- Assignments like a=b; may not happen in one instruction or one cycle, so the other thread may read data which is not compactly written.

Compiler optimization may eliminate the actual test in if (bThread2Done) {... if it is able to figure out that the variable is never set within the loop... there are hint you can give to the compiler that the variable is set outside the code (volatile) which may be needed.

Furthermore you code is implementing what is known as a spin-loop, which means that the threads are going to make the CPU 100% busy if they are locked out, which is really bad for your system performance in general.

OTHER TIPS

If this pseudo code is actually C++, then NO - it's not thread safe.

For example, accessing a variable from two or more threads where one access modifies the variable is undefined behavior. You also invoke member functions for the same object in different threads which is likely not thread safe as well.

By synchronizing the object you can achieve this functionality.

go through : this link

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top