473,395 Members | 1,460 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Multithread Interlocking -- What is wrong with this soluition?

I need a simple multi-thread/process interlock mechanism, that works on
Windows and Linux. However, they have rather different mechanisms. I
put together a system that seems to me to work, and be simple, without
any OS intervention. However, I wanted to ask if anyone saw any
possible leakage. Here it is:

static volatile int lock = 0; // Variable for lock

void controlledAccess() // Function to control access
{
for(;;)
{
if(++lock == 1)
{
// locked section, free access to protected resource
--lock;
break;
}
else
{
--lock;
sleep(1000); // Or whatever }
}
}

Anyone see a way that two threads can get in the critical section?

May 19 '06 #1
4 3626
nd*******@ziplip.com wrote:
I need a simple multi-thread/process interlock mechanism, that works
on Windows and Linux. However, they have rather different mechanisms.
[..]
Anyone see a way that two threads can get in the critical section?


Since C++ does not define any behaviour WRT threads, your post is much
better suited for 'comp.programming.threads'. That said, 'volatile' is
a good first step, as I see it. But do visit 'c.p.t', regardless.

V
--
Please remove capital As from my address when replying by mail
May 19 '06 #2
nd*******@ziplip.com wrote:
I need a simple multi-thread/process interlock mechanism, that works on
Windows and Linux. However, they have rather different mechanisms. I
put together a system that seems to me to work, and be simple, without
any OS intervention. However, I wanted to ask if anyone saw any
possible leakage. Here it is:

static volatile int lock = 0; // Variable for lock

void controlledAccess() // Function to control access
{
for(;;)
{
if(++lock == 1)
{
// locked section, free access to protected resource
--lock;
break;
}
else
{
--lock;
sleep(1000); // Or whatever }
}
}

Anyone see a way that two threads can get in the critical section?


Yes, the ++ and -- operations aren't atomic so you can get race
conditions. Two or more threads could see ++lock return 1, e.g.

t1: load reg,lock // reg and lock equal zero
t1: inc reg // reg equals 1
t2: load reg,lock // reg and lock equal zero
t1: store reg,lock // lock equals 1
t2: inc reg // reg equals 1
t2: store reg,lock // lock equals 1

Also you don't have any memory barriers or compiler
optimization barriers to prevent code movement by the
compiler.

And even if the above weren't a problem, you could have
enough threads such that the lock value never went to zero
and cause starvation of the waiting threads. Putting in
a
while (lock != 0) { sleep(1000); }
before the ++lock would help but not prevent the problem
entirely.

Wait loops like that aren't very efficient or responsive.

Lastly, volatile has no meaning with respect to threading.
So using it won't make a threaded program any more or less
correct.

--
Joe Seigh

When you get lemons, you make lemonade.
When you get hardware, you make software.
May 19 '06 #3

<nd*******@ziplip.com> skrev i en meddelelse
news:11*********************@j73g2000cwa.googlegro ups.com...
I need a simple multi-thread/process interlock mechanism, that works on
Windows and Linux. However, they have rather different mechanisms. I
put together a system that seems to me to work, and be simple, without
any OS intervention. However, I wanted to ask if anyone saw any
possible leakage. Here it is:

static volatile int lock = 0; // Variable for lock

void controlledAccess() // Function to control access
{
for(;;)
{
if(++lock == 1)
{
// locked section, free access to protected resource
--lock;
break;
}
else
{
--lock;
sleep(1000); // Or whatever }
}
}

Anyone see a way that two threads can get in the critical section?


That is absolutely not thread safe :)
2 or more threads could see lock == 1.

For win32 you can use critical section on a single cpu system and semaphores
on linux
the following sample is thread safe on a single cpu'ed system.
For multi cpu'ed systems win32 has functions like InterlockedIncrement(),
InterlockedDecrement(), InterlockedExchange() they will make sure that
processors are instructed to force their memory caches to agree
with main memory (so we're sure both cpus see the same value of an object).

For win32 i made my own critical section, that simply uses
InterlockedEchange
to compare the thread id's and set the lock. You could do the same and make
it work on both platforms.

#if defined (_WIN32)
CRITICAL_SECTION cs;
#else
sem_t semlock;
#endif

DWORD WINAPI SomeThread(LPVOID lpParam) {
int iTrd = (int)lpParam;
while (condition) {
#if defined (_WIN32)
EnterCriticalSection(&cs);
#else
while (sem_wait(&semlock) == -1) {
if (errno != EINTR) {
// failed to lock
}
}
#endif
std::cout << "Thread " << iTrd << " says: Hello World!" <<
std::endl;
#if defined (_WIN32)
LeaveCriticalSection(&cs);
#else
if (sem_post(&semlock) == -1) {
// failed to unlock
}
#endif
Sleep(200);
}
}

void main() {
#if defined (_WIN32)
InitializeCriticalSection(&cs);
#else
if (sem_init(&semlock, 0, 1) == -1) {
// failed to init
}
#endif
for (int i=0; i<max_trd; i++) {
CreateThread(params);
}
while (condition) {
// program main loop
}
#if defined (_WIN32)
DeleteCriticalSection(&cs);
#else
if (sem_destroy(&semlock) == -1) {
// failed
}
#endif
}

I hope this was any help to you :)

//eric
May 19 '06 #4
nd*******@ziplip.com wrote:
I need a simple multi-thread/process interlock mechanism, that works on
Windows and Linux. However, they have rather different mechanisms.

[snip]

In addition to what the others have said, you might consider
Boost.Threads, which is primitive but works on POSIX-style UNIX and on
Windows. See:

http://boost.org/doc/html/threads.html

Cheers! --M

May 19 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Alice | last post by:
Hello I have four multithread windows applications(vb.net) interacting and running on the same machine(windows 2000 with .net framework 1.0). All of them start a new thread each time Filewatcher's...
0
by: r_obert | last post by:
Hello, I'm trying to create a worker thread for my VC++ program, and was wondering whether I should be linking with the Multithread /MT or Multithread DLL /MD option? I'm not quite sure, in...
4
by: zbcong | last post by:
Hello: I write a multithread c# socket server,it is a winform application,there is a richtextbox control and button,when the button is click,the server begin to listen the socket port,waiting for a...
2
by: zhebincong | last post by:
Hello: I write a multithread c# socket server,it is a winform application,there is a richtextbox control and button,when the button is click,the server begin to listen the socket port,waiting...
0
by: fred | last post by:
I need some help in trying to understand how to make myCollection (inherited from CollectionBase) multithread safe. Taking my implementation of the Add Sub and a readonly property Item. Public...
6
by: jmartin | last post by:
Hi, I have made a multithread version of a program (load a file into database), and with two processors I get the double of time in the multithread than in the process (unithread) version. I...
0
by: Gordon Cone | last post by:
I am currently debugging a deadlock in a multithread C# application. It makes lots of calls to legacy unmanaged code. The application runs on windows sever 2003 and uses the sever version of the...
0
by: Gordon Cone | last post by:
I am currently debugging a deadlock in a multithread C# application. It makes lots of calls to legacy unmanaged code. The application runs on windows sever 2003 and uses the sever version of the...
2
by: tikcireviva | last post by:
Hi Guys, I've done a mulithread queue implementation on stl<queue>, my developement environment is on VC6 as well as FC3. Let's talks about the win32 side. The suspected memory leak is find...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.