-1

I met some confusions when writing a C program.

My scenario has 2 thread but they run serial, so at one time there's single thread. I want to save a parameter in my first thread and I want to get it in my second thread. (pthread here)

So is there anyway to realize this? Public static parameter will be recycled when the thread ends because it belongs to the current thread. I want to save a value or pointer in current process instead of thread so that I can attach it in my next thread...

Is there any possible way to realize this?

Thanks so much!

Jiddu.K
  • 69
  • 9
  • 2
    What's the point of running two threads sequentially? – Jonathon Reinhart Jan 30 '18 at 03:13
  • @JonathonReinhart It's a specific scenario... It's a Batch job which have several "steps". each step is a thread and the batch job can only be run sequentially. I want to transmit values between my steps(threads) :-) – Jiddu.K Jan 30 '18 at 03:17
  • 1
    What do you mean by “public static parameter”? – Jonathan Leffler Jan 30 '18 at 03:33
  • 2
    If your scenario is fixed, you can store the data in any convenient place. You’ve not shown any code so we can’t tell if you do create, join, create, join in the main thread or if you do create, create, join, join, or something else. We can’t tell how thread 2 knows when it can run. But your synchronization problems are very limited; it should be easy to manage with pointers passed to the thread functions or with file scope variables, or even global variables. – Jonathan Leffler Jan 30 '18 at 03:37
  • 1
    @Jiddu.K but if it's sequentially why bother with threads? Why not just do all the steps in order? – user253751 Jan 30 '18 at 03:40
  • I think you used function static. Instead of that use file static – Rajesh Jan 30 '18 at 04:42
  • you could always used a shared global variable, and protect it with a mutex in case your threads do happen to run in parallel – bruceg Jan 30 '18 at 06:04
  • @immibis I cannot control it... batch jobs are scheduled by OS(I'm on a mainframe system...), it will assign a thread for each step. That's the reason... – Jiddu.K Jan 31 '18 at 07:48

1 Answers1

0

Threads share the memory. Use a variable (either global, local to the creating thread, or at the heap) and pass a pointer to both threads that points to that very variable.

Matthias
  • 8,018
  • 2
  • 27
  • 53