473,800 Members | 2,725 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 controlledAcces s() // 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 3646
nd*******@zipli p.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.programmi ng.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*******@zipli p.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 controlledAcces s() // 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*******@zipl ip.com> skrev i en meddelelse
news:11******** *************@j 73g2000cwa.goog legroups.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 controlledAcces s() // 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 InterlockedIncr ement(),
InterlockedDecr ement(), InterlockedExch ange() 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
InterlockedEcha nge
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_SECTIO N cs;
#else
sem_t semlock;
#endif

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

void main() {
#if defined (_WIN32)
InitializeCriti calSection(&cs) ;
#else
if (sem_init(&seml ock, 0, 1) == -1) {
// failed to init
}
#endif
for (int i=0; i<max_trd; i++) {
CreateThread(pa rams);
}
while (condition) {
// program main loop
}
#if defined (_WIN32)
DeleteCriticalS ection(&cs);
#else
if (sem_destroy(&s emlock) == -1) {
// failed
}
#endif
}

I hope this was any help to you :)

//eric
May 19 '06 #4
nd*******@zipli p.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
1619
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 created or deleted event is fired. One of these application writes data into word documents also in multithread fashion. Sometimes the created and the deleted events of FileWatcher are not fired in one application - not the same one each time. Any...
0
1865
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 layman's terms, what the difference is. When I build with Multithread DLL, the linker complains about not being able to find a bunch of "unresolved external symbols" associated with nafxcwd.lib.
4
7091
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 incoming connection,the relative code snipprt as following:: private IPAddress myIP=IPAddress.Parse("127.0.0.1"); private IPEndPoint myServer; private Socket socket; private Socket accSocket; private System.Windows.Forms.Button button2;...
2
26521
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 for a incoming connection,the relative code snipprt as following:: private IPAddress myIP=IPAddress.Parse("127.0.0.1");
0
1319
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 Sub Add(ByVal aDoc As myDocument) List.Add(aDoc) End Sub Can I make this multithread safe by and is this the best way to do it.
6
2825
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 have done the test of creating a unique thread that does the same code that the process version of the program and it takes more time that the process without creating the thread.
0
1403
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 CLR. The application runs on ..NET 1.1 SP1. When the deadlock happens the process is using 0 CPU. I was able to collect crash dumps and have been trying to make sense out of them using windbg.
0
2748
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 CLR. The application runs on ..NET 1.1 SP1. When the deadlock happens the process is using 0 CPU. I was able to collect crash dumps and have been trying to make sense out of them using windbg.
2
5310
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 after I've run through my unit test cases. Test Case:
0
9690
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10274
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10251
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10033
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9085
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7576
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6811
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5469
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
2945
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.