Safely access local static variable from a detached thread - multithreading

I have a function(say func()) in which i have a local static variable A. Apart from that, i have a detached thread which calls func() and accesses A. Now, when the main() returns , that local static variable A gets destroyed but the detached thread is still running as it will be destroyed by C++ Runtime.
What's the best way I can ensure that my detached thread doesn't access destroyed local static variable A?

Related

JBPM - Locking When Accessing KieSession From Different Thread

I am doing an upgrade from JBPM 3 to 7. The Process Instances runs on a different thread, Sometimes the UI thread needs to access the process Instance via the KIESession. If I try to execute an operation for example sending a signal the UI is blocked until the process instances finish.
I noticed this also happens if I try to about the process Instance, get the status of the the ProcessInstance and get a variable from the process Instance.
I looked further into it and the PersistableRunner.execute() is synchronized .
FYI I am using the per-process Instance strategy.
Is there a way to get around this issue?
A snippet of the thread DUMP:
java.lang.Thread.State: BLOCKED
waiting for JBPM-Processor-5692548#955268 to release lock on <0xb176> (a org.drools.persistence.PersistableRunner)
at org.drools.persistence.PersistableRunner.execute(PersistableRunner.java:400)
at org.drools.persistence.PersistableRunner.execute(PersistableRunner.java:68)
I tried using the singleton strategy
I would like to be able to access a running KieSession from a different threat without being blocked.

Are environment variables (created using process.env) shared between parent & child node processes?

I'm wondering why the environment variables created using process.env.SOME_VARIABLE in main node process are available in any child processes created using Node's Fork API?
To give you an example, I am building a desktop application using Electron. In that application, I am setting an envrionment variable for proxy settings through the UI using code something like the following:
process.env.HTTPS_PROXY = 'proxy server url';
Now from this application I need to run some tasks in the background and for that I am launching new processes using Node's Fork API. What I noticed is that when I print the value of this variable in the child process, I am getting the value I set in the UI (parent process).
It is my understanding that when I spawn a child process using Fork, a new process is created which is completely independent of the parent process (except for the IPC channel created between them). If these processes are independent of each other, then how come these environment variables that I define in the parent process are available in the child process?
You are partially correct. Whenever the fork() process is called, the new child process is independent, as you rightly said apart from the IPC. But the key here is that this child inherits its "environment" from its parent. So essentially, any 'environment' variable in parent would be a part of child but any 'shell' variable will not be. Similar concept applies for 'exported' variables also.

Start a thread inside an Azure Service Fabric actor?

I know that actors inside Service Fabric are single-threaded. But suppose I start a new thread inside an actor method, what will happen then? Will an actor be deactivated even though the spawned thread is still executing?
According to the documentation, an actor is deactivated when it has not been 'used' for some time. 'Used' in this context means either:
receiving a call
IRemindable.ReceiveReminderAsync being invoked
So it seems that the new thread I started is not taken into account. But maybe someone can confirm this?
Actors are just object.
The Actor will be deactivated and it becomes available for garbage collection.
Actual threads in the OS (when running) keep running until they complete or terminate. Their managed representation can be collected, but this doesn't affect the actual thread.
Also, threads spawned inside an Actor are not tracked in any way, so you're responsible to manage their life cycle yourself.
Exactly.
When you start a new thread, the original thread(The actor) will continue running and go out of scope, and the spanned thread continue running. look what happens then:
When an actor receive a call, the thread handling this call will acquire a lock using a SemaphoreSlim to handle the actor object, if another thread has already acquired the lock, the current thread will wait for its release, so that it can continue once free.
Once the lock is acquired, the thread will execute and return from the method called, and them release the lock for the following thread to continue.
When you span a new thread as part of the actor logic, it will just run as part of the service process, but the problem here is that once you leave the method scope, you won't have control of this thread anymore, but it will keep running, and for the actor runtime the task has finished, the next actor call will create another thread, and the things will keep going.
The problem will start when:
You don't have control how many threads are running, your services will start consuming too much memory and SF might try to balance the actors\services across instances, because it does not know about these threads, if it move the actor service, all you threads will be aborted and you loose these operations.
The spanned thread from previous call will compete with the new thread for the next actor call.
If the new thread uses the actor data to continue other operation both, the spanned thread and the actor thread will face concurrency issues, in cases where no exception happens you will have strange behaviors where you can't investigate easily. For example, one thread changing a value being used by the other.
And many other concurrency issues you might face
In scenarios where you might(think) need another thread you could:
Create another actor to handle the task
Create a message in a queue to be processed by another service
Do the task as part of the actor call.

C++11 thread event : std::future vs std::condition_variable

I'm writing a network test program.
The idea is to have 2 threads. The client and the server.
I want to add some eventing between the 2 threads.
Basicly
Main thread runs the server and creates a new thread for client.
Server thread waits for client to connect.
Client thread sends some data and notifies the server thread.
Client Thread waits.
Server reads the data. Checks if data is intact and notifies the client thread to send more data.
Repeat a number of times in a loop, but server does not know how many times.
After all the data has been send, client thread notifies server thread to exit his loop. Server thread ( main thread joins the client thread. )
I have implemented this using a global std::condition_variable and global variables and it works. I'm writing multiple of these tests functions. Each test function does what I described above but with different data.
Here are some questions that I have:
I found std::promise and std::future. I like the fact that it waits for a value to be set in another thread. Could i use this instead of std::condition_variable? In general, what are use cases for using one method over another when waiting for a variable to be set? Differences, advantages/disadvantages?
Would it be better to declare the std::condition_variable and the variables locally in each test function and pass references to the thread instead of using global variables? For some reason I don't like using global variables.. What would be a better practice?
Do you need to join a thread if you are certain it will end before the main thread? My client thread notifies the server thread ( main thread ) when it is done sending and will exit, So really the server thread is waiting for the client thread to exit. Do i still need to join it in the main thread?

Get Current Thread Handle

I have problem in Delphi application with determining current application (current Thread) handle. I know that I can get Current Thread ID with Windows API function GetCurrentThreadID, but I need current Thread handle to use as param for another Windows API function that is SuspendThread.
Actually what I am trying to do is to make one of my old dll's made for hooking API functions located in kernel32.dll like OpenProcess or TerminateProcessto also do hook for SuspendProcess. Hook is located in dll file and using SetWindowsHookEx to be injected in running processes then finding base address of target functions.
I had no problem with hooking functions like TerminateProcess because it needs process ID as param that is easy to obtain in main application using GetCurrentProcessID. To make similar hook for SuspendThread function i need to pass thread handle as param.
Only place where I found thread handle is PROCESS_INFORMATION structure that contains
typedef struct _PROCESS_INFORMATION { // pi
HANDLE hProcess;
HANDLE hThread;
DWORD dwProcessId;
DWORD dwThreadId;
} PROCESS_INFORMATION;
but problem is that this structure is available only after creating process with CreateProcess API function. Main goal is to prevent program users to use different tools available online like ProcessExplorer etc to terminate process. I acheived that with success hooking TerminateProcess API calls and preventing that way closing my app but Suspend option in those process exploring tools can Suspend my process. It is internet kiosk application and it is vital that users can't close that application. Applications is currently running in Windows XP and it has to be run on administrator account because other apps that users are using after logging in my application requires administrator account to operate, so I can't simply run my application under restricted user.
Is there any way that I can get my main application main thread handle in Delphi ?
Thanks in advance
The only safe way to call SuspendThread is with a handle to the current thread. Suspending any other thread is a bad idea. To get a handle to the current thread, just call GetCurrentThread. You can use it pretty much anywhere a thread handle is required. But don't give that handle to another thread — it's a special "pseudo-handle" that always means "current thread," no matter which thread has it.
You can use OpenThread or DuplicateHandle to get a "real" thread handle, but that probably won't get you where you want to go. You won't be able to recognize attempts to suspend your thread or process because the handle another program uses to suspend your thread won't necessarily be the same value that you got when you called OpenThread. Handles are only meaningful within the process that opened them, and it's possible to acquire multiple handles to the same thing, and that may or may not yield the same value each time.
Instead, call GetThreadId to get the ID of the thread being suspended, and then see whether it matches any of your program's thread IDs. Thread IDs uniquely identify threads; handles don't. Likewise for process IDs and handles.
If you have the thread ID, you can get a handle for it using OpenThread:
HANDLE WINAPI OpenThread(
__in DWORD dwDesiredAccess,
__in BOOL bInheritHandle,
__in DWORD dwThreadId
);

Resources