473,408 Members | 2,734 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,408 software developers and data experts.

Seriliazing threads

72
Hi All,

I need some clarification on on mutex.

Is it possible to use an normal locking (As shown in below code) to serialize access to critical section in threads.

Expand|Select|Wrap|Line Numbers
  1. int lock;
  2. if(lock!= 1){
  3.    lock++;
  4.    //do something here
  5.    lock--;
  6.  
if we cant use this to serialize threads, Can you please explain me or give me a pointer where i can read on this.

Thanks in adavance

Reagards,
Manjunath
Jun 9 '10 #1
5 2282
weaknessforcats
9,208 Expert Mod 8TB
Nope, this won't work.

That's because lock++ and lock-- are a series of machine instructions. In a multithreaded program, you can be interrupted at any machine instruction. Therefore, one thread could get the lock value and get interupted before the ++ was applied and the value returned to the variable. That makes another thread able to get the sam lock value. That's your race condition.

What you need is a function that cannot be interupted. These functions are provided by the operating system that you are using. What they do is stop the entire operating system except for one thread. Then that thread that do lock++. After that the operating system must be re-enabled to run many threads.

This is called a critical section.

For Windows it looks like:

Expand|Select|Wrap|Line Numbers
  1. CRITICAL_SECTION  var;
  2.  
  3. InitializeCriticalSectio(&var);  //initialize var
  4.  
  5. EnterCriticalSection(&var);
  6. //All other threads are blocked
  7.  
  8. ++lock;  //set your lock value
  9.  
  10. LeaveCriticalSection(&var);
  11.  
  12. //the lock value is guaranteed unique
When you are done with var you will need delete the critical section.

This is all covered in Windows via C/C++ by Jeffrey Richter.

If you are not using Windows, then I can't help you but I do know the principle of creating, entering and leaving critical sections still applies.

Lastly, a critical section only applies to a single process. If you need to syunchronize multiple processes, then you need to research using a mutex.
Jun 9 '10 #2
donbock
2,426 Expert 2GB
You cannot reliably serialize threads through C instructions alone -- you need library functions that make use of local processor or operating system features.

For example, suppose lock is initially 0. One thread reaches line 2 and determines that execution should flow to line 3. However, at this point another thread takes over. This new thread also finds lock to be 0 and proceeds through line 3 to line 4. Suppose the first thread then wakes up, proceeds through line 3 to line 4. We now have two threads executing the protected code at line 4. Woe is us.

A reliable locking mechanism requires atomic test-and-set, fetch-and-add, compare-and-swap, or similar operation. Many processors provide these features, but there is no portable way to invoke them from C source code.
Jun 9 '10 #3
manjuks
72
Hi thanks weaknessforcats and donbock.
I understood that the above code will not work, I just want to know weather mutex and semaphores are non preemptive?
Wont it these get interrupted in between?
Jun 10 '10 #4
weaknessforcats
9,208 Expert Mod 8TB
Using a mutex or semaphore is non-preemptive provided you use the OS suppplied functions for working with these objects. That is, a preemptive mutex or semaphore is useless. Indedd, it is the non-preemptive quality that prpvides their value.

If you write your own mutex or semaphore code then all bets are off. The OS supplied functions have Ring 0 authority which you do not and are therefore not interruptible.

Note that using a crtical section where you call EnterCriticalSection blocks every other thread in your process forever until you call LeaveCritcalSection. If tou never make that leave call you process is doomed to the current thread forever.

Ideally, you enter the critical section, set your lock value and leave the critical section. From then on you just test the lock value on the various threads. Sice the test is a rewad-only you do not enter a critical section to do the test.
Jun 10 '10 #5
donbock
2,426 Expert 2GB
Preemption within a critical region is possible; in fact that's what makes it so hard to write reliable locking code in C. Locking a critical region in one thread does not prevent the other threads from running -- it only prevents them from entering the locked critical region. The locked-out threads do not need to block on the lock if they can find something useful to do in the meantime.
Jun 10 '10 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: Ronan Viernes | last post by:
Hi, I have created a python script (see below) to count the maximum number of threads per process (by starting new threads continuously until it breaks). ###### #testThread.py import...
0
by: Al Tobey | last post by:
I was building perl 5.8.2 on RedHat Enterprise Linux 3.0 (AS) today and noticed that it included in it's ccflags "-DTHREADS_HAVE_PIDS." I am building with -Dusethreads. With newer Linux...
6
by: m | last post by:
Hello, I have an application that processes thousands of files each day. The filenames and various related file information is retrieved, related filenames are associate and placed in a linked...
34
by: Kovan Akrei | last post by:
Hi, I would like to know how to reuse an object of a thread (if it is possible) in Csharp? I have the following program: using System; using System.Threading; using System.Collections; ...
7
by: Mr. Mountain | last post by:
In the following code I simulate work being done on different threads by sleeping a couple methods for about 40 ms. However, some of these methods that should finish in about 40 -80 ms take as long...
3
by: bygandhi | last post by:
Hi - I am writing a service which will check a process and its threads for their state ( alive or dead ). The process has 5 .net managed threads created using thread.start and each have been...
10
by: [Yosi] | last post by:
I would like to know how threads behavior in .NET . When an application create 4 threads for example start all of them, the OS task manager will execute all 4 thread in deterministic order manes,...
6
by: RahimAsif | last post by:
Hi guys, I would like some advice on thread programming using C#. I am writing an application that communicates with a panel over ethernet, collects data and writes it to a file. The way the...
3
by: mjheitland | last post by:
Hi, I like to know how many threads are used by a Threading.Timer object. When I create a Threading.Timer object calling a short running method every 5 seconds I expected to have one additional...
10
by: Darian | last post by:
Is there a way to find all the thread names that are running in a project? For example, if I have 5 threads T1, T2, T3, T4, T5...and T2, T4, and T5 are running...I want to be able to know that...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
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...
0
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,...
0
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...

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.