working on it ...

Filters

Explore Public Snippets

Sort by

Found 4,914 snippets matching: thread

    public by sTiLL-iLL  307895  0  5  14

    my nonblocking, threadsafe file writer/appender for nodejs. works great with clustered servers, and child processes that write to shared or static file-stores

    my nonblocking, threadsafe file writer/appender for nodejs. works great with clustered servers, and child processes that write to shared or static file-stores: scribbles.js
    // scribbles.js a nonblocking, threadsafe file writer/appender for nodejs
    
    var fs = require('fs'),
    	pth = require('path'),
    	cueMngr = {};
    
    function Scribbles(fileNm) {
    	this.handle = fileNm;
    	this.canWrite = false;
    	this.actionsRoster = [];
    };
    
    var scribbles = Scribbles.prototype;
    
    scribbles.action = function (err, dta, actionCue) {
    	if (err) {
    		throw err;
    	}
    	return actionCue();
    }
    
    scribbles.assign = function (func) {
    	this.action = func;
    	return this;
    }
    
    scribbles.scribble = function (dta, func) {
    	if (this.canWrite) {
    		this.actionCue = dta;
    		if (func) {
    			this.actionsRoster.push(func);
    		}
    	} 
    	else {
    		this.canWrite = true;
    		var slf = this,
    			taskProxy = {};
    		fs.appendFile(this.handle, dta, function (err) {
    			function actionCue() {
    				slf.canWrite = false;
    				if (slf.actionCue) {
    					var dta = slf.actionCue;
    					slf.scribble(dta);
    					slf.actionCue = null;
    				}
    			}
    			slf.action(err, dta, actionCue);
    			while (taskProxy = slf.actionsRoster.shift()) {
    				return taskProxy(err);
    			}
    			if (func) {
    				return func(err);
    			}
    		});
    	}
    	return this;
    };
    
    module.exports = function (fil) {
    	var nm = pth.resolve(fil);
    	return (cueMngr[nm] = cueMngr[nm] || new Scribbles(fil));
    }
    
    

    public by lbottaro  247366  3  7  0

    Lock and synchronization in python

    This example shows how to deal with lock in python parallel programming. Here we want to calculate the disk occupancy for a given directory in Linux OS, evaluating the disk occupancy for any subdirectory using threads. Note the usage of lock mechanism to ensure atomic operation on the total sum.
    import os
    import string
    import threading
    from threading import Thread
    
    disk_usage = 0
    lock = threading.Lock()
    
    for dir in os.popen('ls -d *').readlines():
        print "Dir: " + dir
        t = Thread(target=methodToBeExecutedInParallel, args=(dir,))
        t.start()
        #Join all existing threads to main thread.
        for thread in threading.enumerate():
            if thread is not threading.currentThread():
              thread.join()
        print "Disk usage = " + str(disk_usage)
    
    # Function invoked by each thread
    def methodToBeExecutedInParallel(directory):
        print "Working on dir = " + directory
        cmd = 'du -s ' + directory
        line = os.popen(cmd).readlines()[0]
        dirUsage = int(line.split()[0])
        print "Acquiring lock for "+directory+"..."
        with lock:
            print "Acquired lock for "+directory
            global disk_usage
            disk_usage += dirUsage
        print "Disk usage = " + str(dirUsage)

    public by Lee Wei Yeong  182644  0  4  0

    @ http://www.haskellforall.com/2013/06/from-zero-to-cooperative-threads-in-33.html

    @ http://www.haskellforall.com/2013/06/from-zero-to-cooperative-threads-in-33.html: free-monad-transform.hs
    data FreeF f a x = Pure a | Free (f x)
    
    newtype FreeT f m a =
        FreeT { runFreeT :: m (FreeF f a (FreeT f m a)) }
    
    instance (Functor f, Monad m) => Monad (FreeT f m) where
        return a = FreeT (return (Pure a))
        FreeT m >>= f = FreeT $ m >>= \v -> case v of
            Pure a -> runFreeT (f a)
            Free w -> return (Free (fmap (>>= f) w))
    
    instance MonadTrans (FreeT f) where
        lift = FreeT . liftM Pure
    
    liftF :: (Functor f, Monad m) => f r -> FreeT f m r
    liftF x = FreeT (return (Free (fmap return x)))
    
    

    public by LongBeard  129652  1  3  0

    Variable amount of BackgroundWorker Threads

    Variable amount of BackgroundWorker Threads: varBgWorkerThreads.cs
            private BackgroundWorker[] Workers;                              
            private int MaxWorkers = 10;                                             
            private Queue<string> Clients = new Queue<string>();
            
            private void _StartNewClient(BackgroundWorker bw)
            {
                if (Clients.Count > 0)
                {
                    string md5nummer = Clients.Dequeue();
                    Debug.WriteLine("Starting " + md5nummer);
                    bw.RunWorkerAsync(md5nummer);
                }
                if (Clients.Count == 0)
                {
    
                    
                }
             
            }
    		
            //BackgroundWorker ~> Task
            private void bw_DoWork(object sender, DoWorkEventArgs e)
            {
                Debug.WriteLine("Working " + e.Argument.ToString());
                ~DO SMTH
                Debug.WriteLine("Worker # " + e.Argument.ToString());
                e.Result = e.Argument.ToString();
            }
    		
            //Background-Worker-Finished
            private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
            {
                solved++;
                if (Clients.Count > 0)
                {
                    Debug.WriteLine("Completed " + e.Result);
                    _StartNewClient((BackgroundWorker)sender);
                }
                if (Clients.Count == 0)
                {
                    bool isAnyBusy = true;
                    for (int i = 0; i < MaxWorkers; i++)
                    {
                        if (Workers[i].IsBusy != true)
                        {
                            isAnyBusy = false;
                        }
                        else { isAnyBusy = true; }
                    }
    
                    if (!isAnyBusy && !finishesMsgShown)
                    {
                        finishesMsgShown = true;
                    }   
                }
    
               
               
            }
            //Start Event
            private void button2_Click(object sender, EventArgs e)
            {
               
                MaxWorkers = int.Parse(numericUpDown1.Value.ToString());
    
                for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
                {
                    Clients.Enqueue(i.ToString());
                    Debug.WriteLine("Added: " + i.ToString());
                }
    
                Workers = new BackgroundWorker[MaxWorkers];
                for (int i = 0; i < MaxWorkers; i++)
                {
                    Workers[i] = new BackgroundWorker();
                    Workers[i].WorkerSupportsCancellation = true;
                    Workers[i].DoWork += new DoWorkEventHandler(bw_DoWork);
                    Workers[i].RunWorkerCompleted += new
                    RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
                    _StartNewClient(Workers[i]);
                }
    
                Debug.WriteLine("Finished Click handler");
            }
    ]]></Code>
        </Snippet>
      </CodeSnippet>
    </CodeSnippets>
    
    

    public by Fresh-Dev  116055  0  3  0

    Threadsafe-GUI Interaction

    Threadsafe-GUI Interaction: threadsafe-gui-actions.cs
      // This method demonstrates a pattern for making thread-safe
    // calls on a Windows Forms control. 
    //
    // If the calling thread is different from the thread that
    // created the TextBox control, this method creates a
    // SetTextCallback and calls itself asynchronously using the
    // Invoke method.
    //
    // If the calling thread is the same as the thread that created
    // the TextBox control, the Text property is set directly. 
    
    private void SetText(string text)
    {
    	// InvokeRequired required compares the thread ID of the
    	// calling thread to the thread ID of the creating thread.
    	// If these threads are different, it returns true.
    	if (this.textBox1.InvokeRequired)
    	{	
    		SetTextCallback d = new SetTextCallback(SetText);
    		this.Invoke(d, new object[] { text });
    	}
    	else
    	{
    		this.textBox1.Text = text;
    	}
    }
    
    

    public by lbottaro  3429  2  6  0

    Basic code to manage threading in python

    This simple example shows how to launch N threads in parallel and handle their execution. Please note the object Thread, where you can define the method to be executed and parameter to be passed. The main program will launch threads and wait for all to complete before continuing execution.
    import datetime
    import threading
    from threading import Thread
    
    my_data_List = ["abc", "123", "bar", "foo"]
    for data in my_data_List:
          print "Going to start thread for data = " + data
          t = Thread(target=methodToRunInParallel, args=(data,))
          t.start()
          #Join all existing threads to main thread.
          for thread in threading.enumerate():
              if thread is not threading.currentThread():
                thread.join()
          print "Completed!"
    
    def methodToRunInParallel(data):
         print "Working on data = " + data
         #Do some stuff here...
         time.sleep(60)
         

    public by sTiLL-iLL @ SniPitz-KND  3822  0  8  12

    BakGRoWnd ThREDiNG WrapAH ObSR.va.BuLL- onny

    
    using System;
    using System.Collections.Generic;
    using System.Threading;
    using System.Threading.Tasks;
    
    public class BGrounda
    {
    	Thread bgThrd;
    
    	public int Progress
    	{
    		get;
    		set;
    	}
    
    	public object Result
    	{
    		get;
    		set;
    	}
    
    	public bool IsActive
    	{
    		get
    		{
    			if (bgThrd != null)
    			{
    				return bgThrd.IsAlive;
    			}
    
    			return false;
    		}
    	}
    
    	public delegate void OnWorkDone(ref int progress, ref object rzlt, params object[] args);
    	public event OnWorkDone jobComplete;
    	List<Task> subscribers = new List<Task>();
    
    	public void RunIT(params object[] arguments)
    	{
    
    			foreach(Task t in subscribers)
    			{
    				bgThrd = new Thread(() => {
    					Task.Factory.StartNew(() => {
    						Task.FromResult(t);
    						this.DoWork.Invoke(ref prog, ref rzlt, arguments);
    						this.jobComplete(100, ref rzlt, "workComplete");
    					});
    				}).Start();
    			}
    
    	}
    
            public void Subscribe(Task obj)
            {
                members.Add(obj);
                return OnWorkHandler;
            }
    
    }                    

    public by MatteoP  2767  3  6  0

    Thread safe update of textbox

    //thread safe component update
    private void log(string text)
    {
        /*
         * Thread-safe method to write things in the textbox
         */
        if (InvokeRequired)
        {
            Invoke(new Action<string>(log), text);
        }
        else
        {
            tbLogging.Text += text + "\n";
        }
    }

    public by cghersi  4084  9  7  3

    Create a TimerTask in C#

    This is the simplest way to create a timertask to execute an operation in another thread without blocking the current thread
    System.Threading.Tasks.Task.Factory.StartNew(() => mymethod(parameter1)); 

    public by Geometry  1843  8  4  0

    GetDeviceService: Finds the GattDeviceService by sensorServiceUuid. IMPORTANT: Has to be called from UI thread the first time the app uses the device to be able to ask the user for permission to use it.

    Finds the GattDeviceService by sensorServiceUuid. IMPORTANT: Has to be called from UI thread the first time the app uses the device to be able to ask the user for permission to use it. Returns the gatt device service of the first device that supports it. Returns null if access is denied. Thrown if there isn't a device which provides the service Uu
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Windows.Devices.Bluetooth.GenericAttributeProfile;
    using Windows.Devices.Enumeration;
    using Windows.Storage.Streams;
    using X2CodingLab.SensorTag.Exceptions;
    using X2CodingLab.Utils;
    
    /// <summary>
    /// Finds the GattDeviceService by sensorServiceUuid.
    /// IMPORTANT: Has to be called from UI thread the first time the app uses the device to be able to ask the user for permission to use it.
    /// </summary>
    /// <returns>Returns the gatt device service of the first device that supports it. Returns null if access is denied.</returns>
    /// <exception cref="DeviceNotFoundException">Thrown if there isn't a device which provides the service Uuid.</exception>
    public async static Task<GattDeviceService> GetDeviceService(string serviceUuid)
    {
        Validator.RequiresNotNullOrEmpty(serviceUuid);
    
        string selector = GattDeviceService.GetDeviceSelectorFromUuid(new Guid(serviceUuid));
        var devices = await DeviceInformation.FindAllAsync(selector);
        DeviceInformation di = devices.FirstOrDefault();
    
        if (di == null)
            throw new DeviceNotFoundException();
    
        return await GattDeviceService.FromIdAsync(di.Id);
    }
    • Public Snippets
    • Channels Snippets