sending multiple types of Runnable Tasks to Executorservice - executorservice

Suppose we have tow types of Task classes( First and Second )implementing Runnable. both of them have an access to a shared object (syncObj) which is supposed to be the Synchronization Object.
we want to use just one Thread pool with any number of thread in such a way that Task of the class First have higher priority to class Second in the Execution. using Countdown latch or any other object how could I implement this problem ?

Related

How ThreaPool reuses threads if thread itself can not be restarted?

I am trying to understand the concept behind the threadpool. Based on my understanding, a thread can not be restarted once completed. One will have to create a new thread in order to execute a new task. If that is the right understanding, does ThreadPool executor recreates new thread for every task that is added?
One will have to create a new thread in order to execute a new task
No. Task are an abstraction of a logical work to perform. It can be typically a function reference/pointer with an ordered list of well-defined parameters (to give to the function). Multiple tasks can be assigned to a given thread. A thread pool is usually a set of threads waiting for new incoming tasks to be executed.
As a result, threads of a given thread-pool are created once.

Win32 Uderstanding semaphore

I'm new to Multithread in Win32. And I have an assignment with Semaphore. But I cannot understand this.
Assume that we have 20 tasks (each task is the same with other tasks). We use semaphore then there's 2 circumstances:
First, there should be have 20 childthreads in order that each thread will handle 1 task.
Or:
Second, there would be have n childthreads. When a thread finishs a task, it will handle another task?
The second problem I counter that I cannot find any samples for Semaphore in Win32(API) but Consonle that I found in MSDN.
Can you help me with the "20 task" and tell me the instruction of writing a Semaphore in WinAPI application (Where should I place CreateSemaphore() function ...)?
Your suggestion will be appreciated.
You can start a thread for every task, which is a common approach, or you can use a "threadpool" where threads are reused. This is up to you. In both scenarios, you may or may not use a semaphore, the difference is only how you start the multiple threads.
Now, concerning your question where to place the CreateSemaphore() function, you should call that before starting any further threads. The reason is that these threads need to access the semaphore, but they can't do that if it doesn't exist yet. You could of course pass it to the other threads, but that again would give you the problem how to pass it safely without any race conditions, which is something that semaphores and other synchronization primitives are there to avoid. In other words, you would only complicate things by creating a chicken-and-egg problem.
Note that if this doesn't help you any further, you should perhaps provide more info. What are the goals? What have you done yourself so far? Any related questions here that you read but that didn't fully present answers to your problem?
Well, if you are contrained to using semaphores only, you could use two semaphores to create an unbounded producer-consumer queue class that you could use to implement a thread pool.
You need a 'SimpleQueue' class for task objects. I assume you either have one already, can easily build one or whatever.
In the ctor of your 'ProducerConsumerQueue' class, (or in main(), or in some factory function that returns a *ProducerConsumerQueue struct, whatever your language has), create a SimpleClass and two semaphores. A 'QueueCount' semaphore, initialized with a count of 0, and a 'QueueAccess' semaphore, initialized with a count of 1.
Add 'push(*task)' and ' *task pop()' methods/memberFunctions/methods to the ProducerConsumerQueue:
In 'push', first call 'WaitForSingleObject()' API on QueueAccess, then push the *task onto the SimpleQueue, then ReleaseSemaphore() API on QueueAccess. This pushes the *task in a thread-safe manner. Then ReleaseSemaphore() on QueueCount - this will signal any waiting threads.
In pop(), first call 'WaitForSingleObject()' API on QueueCount - this ensures that any calling consumer thread has to wait until there is a *task in the queue. Then call 'WaitForSingleObject()' API on QueueAccess, then pop task from the SimpleQueue, then ReleaseSemaphore() API on QueueAccess and return the task - this this thread-safely dequeues the *task.
Once you have created your ProducerConsumerQueue, create some threads to run the tasks. In CreateThread(), pass the same *ProducerConsumerQueue as the 'auxiliary' *void parameter.
In the thread function, cast the *void back to *ProducerConsumerQueue and then just loop around for ever, calling pop() and then running the returned task.
OK, your pool of threads is now ready to do stuff. If you want to run 20 tasks, create them in a loop and push them onto the ProducerConsumerQueue. The threads will then run them all.
You can create as many threads as you want to in the pool, (within reason). As many threads as cores is reasonable for tasks that are CPU-intensive. If the tasks make blocking calls, you may want to create many more threads for quickest overall throughput.
A useful enhancement is to check for 'null' in the thread function loop after each task is received and, if it is null, clean up an exit the thread, so terminating it. This allows the threads to be easily terminated by queueing up nulls, making it easier to shutdown your thread pool, (should you need to), and also to control the number of threads in the pool at runtime.

Thread synchronization for methods?

how many threads will access concurrently if the method is static synchronized and also how many threads will access concurrently if the method is static and finally how many threads will access concurrently if the method is synchronized instance method?
Using static only does not prevent any thread from accessing the method at any time
Using synchronized only, the aquired monitor belongs to the object for which the method was invoked. You still can invoke the same method on other instances of the same class
Using static synchronized, the aquired monitor belongs to the class instead to a specific object, which means that the static method can only be invoked by one thread at the same time, regardless of concrete instances
Consequence: Please note that multiple threads can concurrently invoke two synchronized methods on the same object if one of the methods is static, this could be a pitfall.

Threads, QRunnable and QThreadPool, I can't fit in the details

I know the general theory, Thread, QRunnable and QThreadPool. How does it all fit in ? I mean when an instance of QRunnable is created, and assigned to the ThreadPool, what does it mean to start a thread ? Can multiple threads access the same QRunnable ? Does one QRunnable necessarily map one-to-one with one worker thread ?
QRunnable encapsulates a task that you want performed in a separate thread. If you need to know which thread is running that task or share it between threads, then you are probably doing something more complicated than what QThreadPool is designed to empower. In that case, you would create custom behavior using QThread directly. "Starting" a QRunnable with a QThreadPool is analogous to queueing that task for an available thread in the pool. Whereas, starting a QThread actually allocates a new OS thread and executes it.
The thread pool will manage a finite number of threads with a work queue of QRunnable instances. As a thread becomes available, it will be assigned a QRunnable to process. You don't need to explicitly create any QThread instances if you are using QThreadPool with QRunnable. Note that you still must ensure that shared resources are synchronized (e.g. with a QMutex, QMutexLocker, QReadWriteLock, QSemaphore, and/or QWaitCondition) when used in QRunnable instances.

writing a thread(educational purpose)

Sorry if this is a duplicate...
I have a task to write a thread. And the question is - what a good thread class should contain. I looked through Java implementation and some other, but since it is just an educational project, I wouldn't want to make it too complex. If you can tell or point me to source witch contains required information, I would be very grateful.
Simple thread class consists of following along with threadManager class for easier management of multiple threads
Thread class:
Constructor
function to execute thread
Check if thread is running and process thread's output, if any is present. Returns
TRUE if the thread is still executing, FALSE if it's finished.
Wait until the thread exits
ThreadManager class:
Constructor
Add an existing thread to the manager queue.
Remove a thread from the manager queues.
Process all threads. Returns the number of threads that are still running.
Create and start a new thread. Returns the ID assigned to the thread or FALSE on error.
Remove a finished thread from the internal queue and return it. Returns FALSE if there are no threads that have completed execution.
On the highest level of abstraction you can think about the thread as a combinration of:
Finite-state machine to represent thread's state
Queue of tasks to proceed
Scheduler which can manage threads (start, pause, notify etc ..). Scheduler can be OS level scheduler or some custom scheduler, for example, on the VM level - so called "green threads".
To be more specific, I would recommend to look at Erlang VM. Sources are available online and you can go through their implementantion for "green threads" which are extremely lightweight.
Erlang Downloads

Resources