10 years, 10 months ago.

How to input global variable to a thread

My code has 3 threads which the first thread's output value need to be fed in to the second thread and that thread's output needs to be fed in to the third thread. I am intended to make all the variables that are to be used in the code to be set as global variable and hence all threads can use the updated variables in order to output updated values. I need to know how to get global variables into threads. As I know very little about making threaded codes, it would be much appreciated if any basics of threading is provided. Thank you very much for being attending to my question.

1 Answer

10 years, 10 months ago.

Threading is one of the most complex areas of programming so you are unlikely to get a detailed enough answer here to grasp even the basics.

But to answer your question, any thread can access any global variable currently in scope. There is no notion of passing variables to a thread.

Take the following class:

class Example {
      public:
           string getGlobalVar() {
                 return globalvar;
           }

           void setGlobalVar(string newvar) {
                  globalvar = newvar;
           }
      private:
           string globalvar;
}

It has a single global variable with a getter and setter function, any thread can call either the getter or setter at any time. For your threads to read and modify the global variable in a particular order you are going to have to implement some synchronisation (I am not sure what synchronisation mbed provides). You will also need to make sure that no thread can read while another is writing (more synchronisation).

What are you trying to do? Are you sure that you need three threads?