better solution for setting max threads to hold main thread?

  • Last Update :
  • Techknowledgy :

I want to put a cap on the number of threads (jobs) that can be run at once, say 3 and once that limit is reached it holds the main thread. When one of the threads ends it allows the main thread to continue and pickup another job.

# Wait
for thread count to reduce before continuing
while threading.active_count() >= self.max_threads:
   pass

server.py

import socket
import sys
import urllib, urllib2
import threading
import cPickle

from supply
import supply

class supply_thread(threading.Thread):

   def __init__(self, _sock):
   threading.Thread.__init__(self)
self.__socket = _sock

def run(self):
   data = self.readline()
self.__socket.close()
new_supply = supply.supply(data)
new_supply.run()

def readline(self):
   ""
" read data sent from webserver and decode it "
""

data = self.__socket.recv(1024)
if data:
   data = cPickle.loads(data)
return data

class server:

   def __init__(self):
   # # Socket Vars
self.__socket = None
self.HOST = ''
self.PORT = 50007
self.name = socket.gethostname()

self.max_jobs = 3

def listen(self):
   ""
" Listen for a connection from the webserver "
""

self.__socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Allows quick connection from the same address
self.__socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

self.__socket.bind((self.HOST, self.PORT))
return self.__socket.listen(1)

def connect(self):
   webserver = self.__socket.accept()[0]
print 'Connected by', webserver

new_thread = supply_thread(webserver)
print 'Starting thread', new_thread.getName()

new_thread.start()

def close(self):
   return self.__socket.close()

def run(self):
   import time

while True:
   print(sys.version)

# Wait
for connection from Webserver
self.listen()

time.sleep(3)

# Let the Webserver know I 'm avilable
self.status(status = 'Available')

print 'Waiting for connection...'
self.connect()

print 'thread count:', threading.enumerate()
print 'thread count:', threading.active_count()

while threading.active_count() >= self.max_jobs:
   pass

def status(self, status = 'Available'):
   computer_name = socket.gethostname()
svcURL = "http://localhost:8000/init/default/server"
params = {
   'computer_name': computer_name,
   'status': status,
   'max_jobs': self.max_jobs
}
svcHandle = urllib2.urlopen(svcURL, urllib.urlencode(params))

Suggestion : 2

Last updated 2021-11-10 UTC.

Kotlin

class MainActivity : Activity() {
    // ...
    inner class MyAsyncTask : AsyncTask<Unit, Unit, String>() {
        override fun doInBackground(vararg params: Unit): String {...}
        override fun onPostExecute(result: String) {...}
    }
}

Java

public class MainActivity extends Activity {
  // ...
  public class MyAsyncTask extends AsyncTask<Void, Void, String>   {
    @Override protected String doInBackground(Void... params) {...}
    @Override protected void onPostExecute(String result) {...}
  }
}

Suggestion : 3

04/27/2022

  • The actual number of query requests can exceed the value set in max worker threads in which case SQL Server pools the worker threads so that the next available worker thread can handle the request. A worker thread is assigned only to active requests and is released once the request is serviced. This happens even if the user session/connection on which the request was made remains open.

  • The max worker threads server configuration option does not limit all threads that may be spawned inside the engine. System threads required for tasks such as LazyWriter, Checkpoint, Log Writer, Service Broker, Lock Manager, or others are spawned outside this limit. Availability Groups use some of the worker threads from within the max worker thread limit but also use system threads (see Thread Usage by Availability Groups ) If the number of threads configured is being exceeded, the following query will provide information about the system tasks that have spawned the additional threads.

SELECT s.session_id, r.command, r.status,
   r.wait_type, r.scheduler_id, w.worker_address,
   w.is_preemptive, w.state, t.task_state,
   t.session_id, t.exec_context_id, t.request_id
FROM sys.dm_exec_sessions AS s
INNER JOIN sys.dm_exec_requests AS r
ON s.session_id = r.session_id
INNER JOIN sys.dm_os_tasks AS t
ON r.task_address = t.task_address
INNER JOIN sys.dm_os_workers AS w
ON t.worker_address = w.worker_address
WHERE s.is_user_process = 0;
  1. Connect to the Database Engine.

  2. From the Standard bar, click New Query.

  3. Copy and paste the following example into the query window and click Execute. This example shows how to use sp_configure to configure the max worker threads option to 900.

USE AdventureWorks2012;
GO
EXEC sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
EXEC sp_configure 'max worker threads', 900;
GO
RECONFIGURE;
GO

Suggestion : 4

In this article, you will learn about some common scenarios in Android development where threading becomes essential and some simple solutions that can be applied to those scenarios and more.,I hope you will find this article useful when working on your next Android project. Share with us your experience of threading in Android or any use case where the above solutions work well—or don’t, for that matter—in the comments below.,A Handler is a component that can be attached to a thread and then made to perform some action on that thread via simple messages or Runnable tasks. It works in conjunction with another component, Looper, which is in charge of message processing in a particular thread.,EventBus, a popular library by GreenRobot, enables components to safely communicate with one another. Since our use case is one where we only want to update the UI, this can be the simplest and safest choice.

Sample usage:

public class ExampleActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        new MyTask().execute(url);
    }

    private class MyTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            String url = params[0];
            return doSomeWork(url);
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            // do something with result 
        }
    }
}

With RxJava, you first create an observable:

Observable.create((ObservableOnSubscribe<Data>) e -> {
    Data data = mRestApi.getData();
    e.onNext(data);
})

You chain on the observable with these two functions:

.subscribeOn(Schedulers.io())
   .observeOn(AndroidSchedulers.mainThread()

Suggestion : 5

Last Updated : 25 Jun, 2022

t1 thread priority: 5
t2 thread priority: 5
t3 thread priority: 5
t1 thread priority: 2
t2 thread priority: 5
t3 thread priority: 8
Currently Executing Thread: main
Main thread priority: 5
Main thread priority: 10

main thread priority: 6
t1 thread priority: 6

Suggestion : 6

The many-to-many model multiplexes any number of user threads onto an equal or smaller number of kernel threads, combining the best features of the one-to-one and many-to-one models.,For example in a word processor, a background thread may check spelling and grammar while a foreground thread processes user input ( keystrokes ), while yet a third thread loads images from the hard drive, and a fourth does periodic automatic backups of the file being edited.,Individual processes may be allocated variable numbers of kernel threads, depending on the number of CPUs present and other factors. ,Data parallelism divides the data up amongst multiple cores ( threads ), and performs the same task on each subset of the data. For example dividing a large image up into pieces and performing the same digital image processing on each piece on different cores.

      #pragma omp parallel {
         /* some parallel code here */
      }

Suggestion : 7

GCD handles thread creation and management well. It also helps you to keep the total number of threads in your app under control and not cause any leaks.,Choosing the right option to make your code thread-safe is key to the correctness of the app’s state. Using mutexes to synchronize access to code blocks is as important as creating high-throughput reads with protected writes using reader–writer locks.,Each process has at least one thread. In iOS, the primary thread on which the process is started is commonly referred to as the main thread. This is the thread in which all UI elements are created and managed. All interrupts related to user interaction are ultimately dispatched to the UI thread where the handler code is written—your IBAction methods are all executed in the main thread.,Each thread consumes approximately 1 KB of memory in kernel space. The memory is used to store the data structures and attributes pertaining to the thread. This is wired memory and cannot be paged.

Example 4-1. Change thread stack size
+(NSThread * ) createThreadWithTarget: (id) target selector: (SEL) selector
object: (id) argument stackSize: (NSUInteger) size {

   if ((size % 4096) != 0) {
      return nil;
   }
   NSThread * t = [
      [NSThread alloc] initWithTarget: target
      selector: selector object: argument
   ];
   t.stackSize = size;

   return t;
}
Example 4-2. Atomic and nonatomic properties
@property(atomic) NSString * firstName;
@property(nonatomic) NSString * department;
Example 4-3. Using atomic properties across threads
//An entity (partial definition)
@interface HPUser

@property(atomic, copy) NSString * firstName;
@property(atomic, copy) NSString * lastName;

@end

//A service class (declaration omitted for brevity)
@implementation HPUpdaterService

   -
   (void) updateUser: (HPUser * ) user properties: (NSDictionary * ) properties {
      NSString * fn = [properties objectForKey: @ "firstName"];
      if (fn != nil) {
         user.firstName = fn;
      }
      NSString * ln = [properties objectForKey: @ "lastName"];
      if (ln != nil) {
         user.lastName = ln;
      }
   }

@end
Example 4-4. Thread-safe blocks
@implementation HPUpdaterService

   -
   (void) updateUser: (HPUser * ) user properties: (NSDictionary * ) properties {
      @synchronized(user) {
         NSString * fn = [properties objectForKey: @ "firstName"];
         if (fn != nil) {
            user.firstName = fn;
         }
         NSString * ln = [properties objectForKey: @ "lastName"];
         if (ln != nil) {
            user.lastName = ln;
         }
      }
   }

@end
Example 4-5. Using NSLock
@interface ThreadSafeClass() {
   NSLock * lock;
}
@end

   -
   (instancetype) init {
      if (self = [super init]) {
         self - > lock = [NSLock new];
      }
      return self;
   }

   -
   (void) safeMethod {
      [self - > lock lock];

      //Thread-safe code 

      [self - > lock unlock];
   }
Example 4-6. Using NSRecursiveLock
@interface ThreadSafeClass() {
   NSRecursiveLock * lock;
}
@end

   -
   (instancetype) init {
      if (self = [super init]) {
         self - > lock = [NSRecursiveLock new];
      }
      return self;
   }

   -
   (void) safeMethod1 {
      [self - > lock lock];

      [self safeMethod2];

      [self - > lock unlock];
   }

   -
   (void) safeMethod2 {
      [self - > lock lock];

      //Thread-safe code

      [self - > lock unlock];
   }