Reputation: 115
I am fairly new to Win32 programming. I want to create a shared memory between two processes. I already have created shared memory using the Memory Mapping function.
My struct would look this this:
struct sharedMemory
{
int ans1;
int ans2;
BOOLEAN flag1;
};
Now I am able to access this shared memory from different processes, but I am confused on how to apply lock to this shared memory so that only 1 process is able to access the struct member variable.
Upvotes: 4
Views: 3481
Reputation: 503
You can either do one of two things, 1) Create a mutex, and lock it via mutex functions (See MSDN reference) 2) Create or utilize the boolean, true for lock (that is to say some copying, modifying, or using of data is being done) and false for unlock (parent or master thread is dealing with it). That way you can do:
int someThread1(threadData *data)
{
data->lock = true;
/* Do data functions */
data->lock = false;
return 1; //Or whatever you want it to return after checking data
}
int someThread2(threadData *data)
{
data->lock = true;
/* Do data functions */
data->lock = false;
return 1; //Or whatever you want it to return after checking data
}
void *masterThread(void *data)
{
ThreadData * t_Data = (ThreadData*)data;
do
{
if(t_Data->lock == false)
{
/*Do normal operations */
}
else
{
Sleep(10); //Give the CPU a break
//Do whatever else you need
}
}while(someCondition == true);
return 0;
}
I am aware the above isn't quite standard, or perfect. But is just a way you can go about manually managing threads if not using mutex's. Just an Idea/suggestion
Upvotes: 0
Reputation: 52157
By providing a mutex name when calling CreateMutex
, you'll make the mutex visible from other processes.
If another process passes the same name to the CreateMutex
, it will get the existing mutex (instead of creating a new one), which can then be used for inter-process synchronization.
Upvotes: 8
Reputation: 6914
Shared memory are just pages of memory that loaded in address space of various programs, so sharing memory has nothing to do with access of process to it. in order to handle this in any OS, including Windows and Posix you should create your own synchronization mechanism.
In order to handle this you have to steps, a process signal another process that data is ready( in Win32 you can use named events, for more information take a look at CreateEvent ) and another step is exclusive access to shared memory through some syncronization mechanism (in Win32 this can be accomplished using named mutexes, for more information see CreateMutex).
Upvotes: 1
Reputation: 3443
Slightly confused, memory mapped files are thread safe. Numerous threads can access one or more file views with read and read/write access.
Anyway, you'd need an inter process lock to allow only one thread to touch your struct (Mutex).
Upvotes: 0