2

I need to know how a thread can send its ID to another thread before it goes to wait state. I thought to pass a variable with its ID but I don't know how to do it.

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
Albert
  • 142
  • 1
  • 8
  • You can use a pipe to write and read from (if I am understanding what you are asking). – C.B. Jan 28 '14 at 19:01

3 Answers3

1

If it's only one thread and its parent, you could use a global variable, as they are shared between all threads. Make it volatile in case you expect concurrent access.

EDIT: I'm not sure if you're using POSIX threads on Linux but you probably have a way to pass a pointer (e.g. to a struct) when creating the thread. It could contain a variable to store its ID or a pointer to a function to call on the parent thread. I know you can do it with Windows threads.

Matthieu
  • 2,736
  • 4
  • 57
  • 87
  • If it's shared between all threads (and you are going to make it `volatile` anyway), then why the restriction of "one thread and its parent?" – Robert Harvey Jan 28 '14 at 19:04
  • Sorry I updated the question after you answered. There are a lot of threads and one main thread (scheduler). I need the last one to know the ID of another threads before they go to sleep. – Albert Jan 28 '14 at 19:06
  • @RobertHarvey if you spawn several threads, you can't use a single variable as the second thread spawned will overwrite it. – Matthieu Jan 28 '14 at 19:06
1

You can create a pointer in the thread which is pointing to the function in the parent (by reference). By the time it goes to wait state then it can just use that pointer to trigger something to its parent.

1

Threads share memory, so you can allocate a global variable and let the child write on it.

Than for the synchronization (aka inform the parent that a value has been written) you have many choices: you can use a semaphore, can send a signal from the thread back to its parent, use a synchronization variable like explained here.

Community
  • 1
  • 1
fede1024
  • 3,099
  • 18
  • 23