hi!

I have a program, and I have 2 threads.
in the first I lock a semaphore, and in the second I have to run some code, but only after the first locked the semaphore.

right now I do it with busy-waiting:

void *thread_proxy_stub(void *arg)
{
  int x;
  // wait untill the main thread will lock the first semaphore:
  while (1)
  {
	x = semctl ( sem1 , 0 , GETNCNT); // get the number of waiting threads.
	if (x == -1) exit(-1); // error - exit.
	if (x > 0) break; // if the main thread locked the first semaphore - break the loop.
	usleep(1); // else - wait milisecond and check again.
  }
  // continue for the code...

Is there any other way to do it?
I need an answer today, so if someone could help me, please do it...
Thanks,
-Nate

Recommended Answers

All 6 Replies

another explanation:

in the main thread the code is stucked right after locking the semaphore (and it's ok...):

// create the thread that will use proxy_stub:
  pthread_create(&tid, NULL, thread_proxy_stub, NULL);

  // lock the semaphore:
  if (semop(sem1, &sb, 1) == -1) exit(1); // on error exit.

the "thread_proxy_stub" should run right after the main thread do the last row.

Read about thread wait and thread signal methods

Read about thread wait and thread signal methods

I know about wait and signal. still cannot find a solution.

Can you explain the problem a bit more clearly ?
This is what I have understood so far. You have some shared memory. Thread 1 locks this memory up. so that when thread 2 access this region he find it locked ?
Is there any thing more to it ?

Can you explain the problem a bit more clearly ?
This is what I have understood so far. You have some shared memory. Thread 1 locks this memory up. so that when thread 2 access this region he find it locked ?
Is there any thing more to it ?

I have to lock a semaphore in the main thread. and right after that I have to run another code.

the problem is, that when I locked the semaphore - the program is stucked - and this is not problem - this is what shuold happen.
that's why I should run the other code in another thread, and check there if the main thread already locked the semaphore. (of course I cannot write it right after the semaphore lock - because it won't run)

and the problem is about semaphores - not shared memory...
Thanks anyway,
-Nate

A better and more efficient way is to create an onTerminate() Even for your thread which is called when the thread A terminates. It will be better manageable & you can pass a pointer to the function in the thread initialization.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.