the variable with the same name in multi threads environment - c++

I have a Class File. I created two threads A and B. In A and B, each thread, I create an auto varible File myfile. And then A and B will operate it. Is that secure? Will it lead to the inconsistent of data?

From the pure memory ressource perspective, it will depend on the scope of your File variables :
If they are local function variables, you are good to go. Each thread of execution owns it own stack, totally separate from other threads, where it create local variables.
If they are static, you are referring to the same global address.
From the file access perspective, it will depends if it is the same file, and if you are writing to it or not.

No, that shouldn't be a problem, simply because each instance of your thread has it's own instance of the variable.
Examine the addresses of the variables to be sure, if they differ (which they will if I understand you correctly), you're fine.
Inconsistencies between threads will only occur, if two threads concurrently access the same variable. Not just 'the same name', but really the same variable.
Now, if the variable was global and both threads were to access it, you'd need some sort of mutual exclusion to prevent data corruption, but auto-variables are safe.

The variables will be distint from each other as each thread will have its own stack, and each instance of the variable will live on that stack.
However, it sounds like you're accessing an underlying filesystem file. If it's the same file and one or both of the threads are writing to the file then this may cause data consistency issues. You'll need to consult the documentation for your operating system to see what it says. If both threads are just reading from the same file then you'll be fine.

Related

How to share a global object between threads?

I have created a class, which has many public functions, some which write data and some that only read data.
It's required that I do this within 3 threads, I have no other option.
I know if I accessed a shared resource just to read, then I don't have to protect, but I don't know if it is any different when I am using a function to read a private variable of the shared resource.
E.g. I am trying to do...
globalObject.readColour();
which is a function that reads the colour of the global object.
Does it mean that I have to secure the thread at this point, or is it okay to just read the value without any risks?
I'm working on mbed, which supports c and c++98.
This question is similar to this one
If all your threads will only read the variable then you don't need mutex (or similar), but if any thread performs a writing operation you should use mutex.

Is A Member Function Thread Safe?

I have in a Server object multiple thread who are doing the same task. Those threads are init with a Server::* routine.
In this routine there is a infinite loop with some treatments.
I was wondering if it was thread safe to use the same method for multiple threads ? No wonder for the fields of the class, If I want to read or write it I will use a mutex. But what about the routine itself ?
Since a function is an address, those thread will be running in the same memory zone ?
Do I need to create a method with same code for every thread ?
Ps: I use std::mutex(&Server::Task, this)
There is no problem with two threads running the same function at the same time (whether it's a member function or not).
In terms of instructions, it's similar to if you had two threads reading the same field at the same time - that's fine, they both get the same value. It's when you have one writing and one reading, or two writing, that you can start to have race conditions.
In C++ every thread is allocated its own call stack. This means that all local variables which exist only in the scope of a given thread's call stack belong to that thread alone. However, in the case of shared data or resources, such as a global data structure or a database, it is possible for different threads to access these at the same time. One solution to this synchronization problem is to use std::mutex, which you are already doing.
While the function itself might be the same address in memory in terms of its place in the table you aren't writing to it from multiple locations, the function itself is immutable and local variables scoped inside that function will be stacked per thread.
If your writes are protected and the fetches don't pull stale data you're as safe as you could possibly need on most architectures and implementations out there.
Behind the scenes, int Server::Task(std::string arg) is very similar to int Server__Task(Server* this, std::string arg). Just like multiple threads can execute the same function, multiple threads can also execute the same member function - even with the same arguments.
A mutex ensures that no conflicting changes are made, and that each thread sees every prior change. But since code does not chance, you don't need a mutex for it, just like you don't need a mutex for string literals.

Shared and local variables C++

I need to implement solution for readers writer problem in file system i'm developing. I was searching on the internet and found out this Wikipedia solution. Since I'm told no starving may exist I chose third solution. Now, I'm new in multithreaded programming and I have one question. How do I sepparate shared and local variables? I wanted to instantiate one ReadersWriters class in every file object that would manage accessing to that file, so every thread need to have it's own prev and current local variables and all of them need to share nreaders variable. I want to place them in ReadersWriters class.
As far as I know there are only two ways for the parent thread to share data with a child thread.
Global Variables
Passing it via a pointer during creation of the child thread.
Obviously new pointers may be tacked onto any existing objects.
Local variables with remain thread local unless you do something to prevent them from being so. Remember that each thread will have its own stack.

What happens if I call an objects member function from a different thread?

If I have an C++ object created in the main thread, and then start another thread, and from that thread I call a public member function of the object I created, what happens?
Is it different if the public function has parameters or if it manipulates private object members?
Does it behave differently on windows, linux or mac os?
What happens if the object is created on the stack?
There are two points that matter:
first, as usual, you need to esnure that the lifetime of the instance exceeds the duration of its usage.
second, access to variables across multiples threads need be synchronized to prevent race conditions.
That's all folks.
Each thread has a own stack and thus you can have concurrent streams of execution. It is your own duty to make the object thread-safe.
It does not matter. However, private members are a candidate for race conditions.
If you create an object on the stack, it won't be accessible from another thread.
If I have an C++ object created in the main thread, and then start another thread, and from that thread I call a public member function of the object I created, what happens?
It depends on lifetime of the object.
If the object is created on heap(dynamic memory using new) then the other thread will access the members of the object correctly(assuming no race conditions) unless the lifetime of the object ended by calling delete in the first thread.
If the object is created on stack(locally) in the first thread then you will have a *Undefined Behavior*if the lifetime of the created object ended before being accessed in second thread.
Why can you access the object on stack in second thread?
Each thread has its own stack and unless the object created on stack of thread is valid and alive You would be trying to access an address location which doesn't point to any valid object in second thread.
Note that each process has an address space and all threads in the same process share the same address space, hence the address of the variable can be accessed in the second thread. However, You need to ensure that address contains a valid object.
Is it different if the public function has parameters or if it manipulates private object members?
Access specifiers and multithreading are not related at all.
Same access specifier rules apply in all threads.
Does it behave differently on windows, linux or mac os?
The answer to #1 is guaranteed on all Operating systems.
Compared to the original behaviour there should be no differences if created on the heap. However there are some culprits of course, usually known under the term "thread safety". If you access the same member from different threads, you have to ensurse that accessing the same resources does not lead to a "race condition".
To avoid race conditions you can use different kind of "locks", for instance mutexes etc. When using using lock objects there is another culprit: The danger of "deadlocks", if two accessors wait for each other and the original lock never gets released.
It will work perfectly well. Objects do not belong to any specific thread and can equally well be called from anywhere.
However, and this is important, calling member function on two threads at the same time will cause problems where you update some data in one thread while reading it in another. You need to either arrange your code to ensure this can't happen, or ensure that your threads coordinate access (using mutex most likely)
What happens is exactly what happens if you call it from the same
thread. The same machine code gets executed. The only potential
difference is that you can have several threads accessing the object at
the same time; it's up to you to protect against this (at least if any
of the threads is modifying the object—otherwise, no protection is
needed).
In the case of an object on the stack, you have to consider lifetime
issues, but this is the case anyway; save a pointer to an object on the
stack in a global variable, then leave the scope where the object was
defined, and the global variable becomes a dangling pointer; trying to
access the object through it is undefined behavior (and calling a
non-static member function on it it is considered using it). Whether
the access is from the same thread or a different thread doesn't change
anything.

boost::thread function execution

How do I use a boost::thread to execute a function with each thread executing in its own memory space. So that when I allocate a new variable with in the function it only lives as an instance in the executing thread.
Just to clarify I want to spawn threads that execute the same method using boost::thread but I do not want to use locks or semaphores I just want it to execute in a separate space.
Anything you allocate inside the thread function is already local to that function, as long as they're not declared as static. Just write your code as normal (avoiding static local variables) and you'll be fine.
If you need to create a thread that is running completely within its own address space, then what you are looking to do is to create a process, not a thread. Threads by definition are points of execution running within the same address space of the parent process.
If you really need to create threads (i.e. there's still memory and other resources shared between threads), but you also need to have a portion of memory dedicated to a specific thread, then you have few options:
1) as ildjarn suggested, have thread procedure allocate local (or dynamic memory) and write your code so that each thread uses this memory that it allocates for itself
2) Take a look at TLS (Thread Local Storage). It is an API that allows you to create "global" variables which are dedicated to a specific thread. Also some variations of C++ have built-in keywords for declaring variables which use TLS under the hood.
Note that in above options you will not get automatic isolation where a thread would not be able to corrupt another threads memory. The only way to get this isolation is to spawn multiple processes (or switch to one of .NET languages and instantiate multiple AppDomains running within the same process).