Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sharing variables between threads

Status
Not open for further replies.

SmileeTiger

Programmer
Mar 13, 2000
200
US
I have created a threading application that has a couple of processes accessing the same variable. I want them to both check the variable to see if the other process is using a shared file. If one is the other sleeps.

This is what I have done thus far:


#include <stdio.h>
#include <stdlib.h>
#include <time.h>


#define FNAME &quot;data.dat&quot; //The file that will be read from and written to
#define MAXREADERS 100
#define MAXWRITERS 100

#define WRITERS 5
#define RUNS 1



void CreateWriter(struct state Reader[], struct state *Writer, int
*WriteLock);


int main()
{
pid_t mainPID;
FILE *inFile, *outFile;
int tmp=0;
int i,pid, NumReaders, NumWriters;
int seed; //Seed for random number gen
int WriteLock=0; //Shows if file is locked for writing

for (i=0; i<WRITERS; i++)
{

Writers.seed = i + (int)pid; //Gives each thread it's //own seed
Writers.who = i;
CreateWriter(Readers, &amp;Writers, &amp;WriteLock);
}

}


void CreateWriter(struct state Reader[], struct state *Writer, int
*WriteLock)
{
int i;

if ( (pid=fork() ) !=0)
{
for (i=0; i<RUNS; i++)
{


sleep(rand_r(&amp;(Writer->seed))%3); //Random sleep before
//starting
while(WriteLock==1) //Checks to see if other writers are writing
{
printf(&quot;Waiting for writer finish&quot;);
sleep(rand_r(&amp;(Writer->seed))%3); //Random sleep
}
//since no one is writing now the writer can lock writing for himself


printf(&quot;\nThe lock var is: %i&quot;,*WriteLock);
*WriteLock=1; //No one else can write
printf(&quot;\nJust locked The lock var is: %i&quot;,*WriteLock);
sleep(rand_r(&amp;(Writer->seed))%3); //Random sleep for a bit
*WriteLock=0; //Let the other process take over
}

}

}

It seems however, that neither process can see the others variables so both assume that they are unlocked at all times.

Any ideas?

Cory
 
Cory,

This would not work as fork creates a copy of the existing
process and also the data area.
You may like to use some kind interprocess communication
functionality like semaphores,shared memory.
Also,fcntl system call F_SETLK options which would lock a
file, please check the man page.


Also additional FYI, instead of fork if you use vfork
the parent and child would use the same data space.
So, if WriteLock is set over in child then
parent can see it and vice-versa.

Hope this may help.

Regards
Deepak

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top