working on it ...

Filters

Explore Public Snippets

Sort by

Found 187 snippets matching: thread-safe

    public by sTiLL-iLL @ SniPitz-KND  4312  1  8  25

    Scribbles.js

    A non-blocking, thread-safe, async file-writer / appender for node.js.... oh yeah, its also faster than grease. Try iT!
    // scribbles.js
    
    var fs = require('fs'),
    	path = require('path'),
    	scribe = null,
    	canWrite = true,
    	roster = [],
    	scribblesQue = {};
    
    function Scribbles(file) {
      this.fPath = file;
      this.react = null;
    }
    
    scribe = Scribbles.prototype;
    scribe.scribble = function(data, reaction) {
    	var proceed = function () {
    		canWrite = true;
    		if (proceed) {
    			var dta = proceed;
    			proceed = null;
    			scribble(dta);
    		}
    	},
    	react = function(err, data, proceed) {
    		if (err) {
    			throw err;
    		}
    		proceed();
    	},
    	assign = function(reaction) {
    		this.react = reaction;
    		return this;
    	};
    	
    	if (!this.canWrite) {
    		proceed = data;
    		if (reaction) {
    			this.roster.push(reaction);
    		}
    		return this;
    	}
    	else {
    		var lazyfunc = null,
    			slf = this;
    		canWrite = false;
    		fs.appendFile(slf.fPath, data, function(err) {
    			proceed();
    			react(err, data, proceed); 
    			while (lazyfunc = roster.shift()) {
    				lazyfunc(err);
    			}
    			if (reaction){
    				reaction(err);
    			}
    		});
    	}
    	return this;
    };
    
    module.exports = function(fileName) {
      var fnm = path.resolve(fileName);
      return scribblesQue[fnm] = scribblesQue[fnm] || new Scribbles(fileName);
    }
    

    public by MatteoP  2769  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 terryc  2207  1  5  0

    Design pattern in Java: singleton

    Implementation of singleton design pattern in Java
    public class Singleton {
    	static Singleton _singleton;
    	
    	static { 
    		_singleton = new Singleton();
    	}
    	
    	private Singleton() {
    	}
    
    	/**
    	 * Retrieve the only instance available in this JVM
    	 */
    	public static Singleton get() { 
    		return _singleton;
    	}
    }

    public by sTiLL-iLL  2622  4  7  11

    C# Threaded Observable TimePeriod

    observable timer with events, threaded and thread-safe for any usage
    
    public IObservable<long> Interval(TimeSpan waitPeriod)
    {
        return Observable.Create<long> (observer => {
            long i = 0;
            object synkMe = new object();
            return new Timer (_ => {
                lock (synkMe)
                {
                    observer.OnNext (i++);
                }
            },
            null, waitPeriod, waitPeriod);
         });
    }    
    
    void Main()
    {
        Interval (TimeSpan.FromSeconds(2.00)).Dump();
    }         

    public by giovanni.gambaro  1743  1  4  1

    Date formatting using ThreadLocal variable

    How to avoid synchronization for a not thread safe classes
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    public class Foo
    {
        // SimpleDateFormat is not thread-safe, so give one to each thread
        private static final ThreadLocal<SimpleDateFormat> formatter = new ThreadLocal<SimpleDateFormat>(){
            @Override
            protected SimpleDateFormat initialValue()
            {
                return new SimpleDateFormat("yyyyMMdd HHmm");
            }
        };
    
        public String formatIt(Date date)
        {
            return formatter.get().format(date);
        }
    }

    public by msdn  120454  0  6  0

    GetInstance: Normal GetInstance() , not thread safe

    Normal GetInstance() , not thread safe Singleton Object
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Runtime.CompilerServices;
    
    private static Singleton uniqueInstance;
    
    /// <summary>
    /// Normal GetInstance() , not thread safe
    /// </summary>
    /// <returns>Singleton Object</returns>
    public static Singleton GetInstance()
    {
        if (uniqueInstance == null)
        {
            Console.WriteLine("Creating Singleton Instance first time .....");
            uniqueInstance = new Singleton();
        }
        else
        {
            Console.WriteLine("Singleton Instance already present .....");
        }
    
        return uniqueInstance;
    }

    public by msdn  1351  0  6  0

    GetInstanceEager: Mostly used, Thread Safe by Default

    Mostly used, Thread Safe by Default
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Runtime.CompilerServices;
    
    private static readonly Singleton uniqueInstanceEager = new Singleton();
    
    /// <summary>
    /// Mostly used, Thread Safe by Default
    /// </summary>
    /// <returns></returns>
    public static Singleton GetInstanceEager()
    {
        return uniqueInstanceEager;
    }

    external by Github  354  0  3  0

    THREAD-SAFETY for every one... simple way to wrap any object with a thread-safe wrapper,

    THREAD-SAFETY for every one... simple way to wrap any object with a thread-safe wrapper, : gistfile1.rb
    class << NSProxy
      def method_added(meth)
      end
    
      def inherited(klass)
      end  
    end
    
    class Proxy < NSProxy
      def self.const_missing(n)
        ::Object.const_get(n)
      end
      
      def self.new(object=nil)
        alloc.initWithTarget(object)
      end
        
      def initWithTarget(target)
        @_target = target
        @_queue = Dispatch::Queue.new("#{target.object_id}-de.mateus.synchronized.proxy")
        self
      end
        
      def method_missing(m, *args, &blk)
        @_queue.sync do
          options = args.select { |arg| arg.is_a?(::Hash) }.first
        
          selector = arguments = nil
          
          if options
            selector  = options.keys.unshift(m).map { |txt| txt.to_s.appendString(':') }.join   
            arguments = options.values.unshift(args.first)
          end
        
          target = @_target
          result = if selector && target.respond_to?(selector)
                      target.__send__(selector, *arguments, &blk)
                    elsif target.respond_to?(m)
                      target.__send__(m, *args, &blk)
                    end
          return result
        end
      end
      
      def inspect
        description
      end
    end
    
    # let try create an dumbass parallel the map 
    class Array
    
      def failed_map(&block)
        return self.to_enum unless block_given?
        
        result = []
        Dispatch::Queue.concurrent.apply(self.count) { |idx| result << block.call(self[idx]) }
        
        NSArray.arrayWithArray(result)
      end
      
      def p_map(&block)
        return self.to_enum unless block_given?
        
        result = Proxy.new([])
        Dispatch::Queue.concurrent.apply(self.count) { |idx| result << block.call(self[idx]) }
        
        NSArray.arrayWithArray(result.to_a)
      end
    end
    
    array = [*0...1000]
    result = array.p_map { |obj| obj + 10 }
    puts result.count           # => 1000
    
    result = array.failed_map { |obj| obj + 10 }
    puts result.count           # => it might returns an shit, you never know.... 988 | 987 | 980... 1000 possibilities
                                # it may even crash...
    
    # let's try out a named parameters method... boommmm every thing works
    content = Proxy.new([*0..1000])
    opts = NSEnumerationConcurrent|NSEnumerationReverse
    content.enumerateObjectsWithOptions(opts, usingBlock:-> obj, idx, stop { puts "#{idx}:\t#{obj}\n" })
    
    

    external by Baran  17  0  1  0

    Creating Thread-Safe Arrays in Swift: http://basememara.com/creating-thread-safe-arrays-in-swift/

    Creating Thread-Safe Arrays in Swift: http://basememara.com/creating-thread-safe-arrays-in-swift/: SynchronizedArray.swift
    import Foundation
    import PlaygroundSupport
    
    /// A thread-safe array.
    public class SynchronizedArray<Element> {
        fileprivate let queue = DispatchQueue(label: "io.zamzam.ZamzamKit.SynchronizedArray", attributes: .concurrent)
        fileprivate var array = [Element]()
    }
    
    // MARK: - Properties
    public extension SynchronizedArray {
    
        /// The first element of the collection.
        var first: Element? {
            var result: Element?
            queue.sync { result = self.array.first }
            return result
        }
    
        /// The last element of the collection.
        var last: Element? {
            var result: Element?
            queue.sync { result = self.array.last }
            return result
        }
    
        /// The number of elements in the array.
        var count: Int {
            var result = 0
            queue.sync { result = self.array.count }
            return result
        }
    
        /// A Boolean value indicating whether the collection is empty.
        var isEmpty: Bool {
            var result = false
            queue.sync { result = self.array.isEmpty }
            return result
        }
    
        /// A textual representation of the array and its elements.
        var description: String {
            var result = ""
            queue.sync { result = self.array.description }
            return result
        }
    }
    
    // MARK: - Immutable
    public extension SynchronizedArray {
        /// Returns the first element of the sequence that satisfies the given predicate or nil if no such element is found.
        ///
        /// - Parameter predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element is a match.
        /// - Returns: The first match or nil if there was no match.
        func first(where predicate: (Element) -> Bool) -> Element? {
            var result: Element?
            queue.sync { result = self.array.first(where: predicate) }
            return result
        }
        
        /// Returns an array containing, in order, the elements of the sequence that satisfy the given predicate.
        ///
        /// - Parameter isIncluded: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element should be included in the returned array.
        /// - Returns: An array of the elements that includeElement allowed.
        func filter(_ isIncluded: (Element) -> Bool) -> [Element] {
            var result = [Element]()
            queue.sync { result = self.array.filter(isIncluded) }
            return result
        }
        
        /// Returns the first index in which an element of the collection satisfies the given predicate.
        ///
        /// - Parameter predicate: A closure that takes an element as its argument and returns a Boolean value that indicates whether the passed element represents a match.
        /// - Returns: The index of the first element for which predicate returns true. If no elements in the collection satisfy the given predicate, returns nil.
        func index(where predicate: (Element) -> Bool) -> Int? {
            var result: Int?
            queue.sync { result = self.array.index(where: predicate) }
            return result
        }
        
        /// Returns the elements of the collection, sorted using the given predicate as the comparison between elements.
        ///
        /// - Parameter areInIncreasingOrder: A predicate that returns true if its first argument should be ordered before its second argument; otherwise, false.
        /// - Returns: A sorted array of the collection’s elements.
        func sorted(by areInIncreasingOrder: (Element, Element) -> Bool) -> [Element] {
            var result = [Element]()
            queue.sync { result = self.array.sorted(by: areInIncreasingOrder) }
            return result
        }
        
        /// Returns an array containing the non-nil results of calling the given transformation with each element of this sequence.
        ///
        /// - Parameter transform: A closure that accepts an element of this sequence as its argument and returns an optional value.
        /// - Returns: An array of the non-nil results of calling transform with each element of the sequence.
        func flatMap<ElementOfResult>(_ transform: (Element) -> ElementOfResult?) -> [ElementOfResult] {
            var result = [ElementOfResult]()
            queue.sync { result = self.array.flatMap(transform) }
            return result
        }
    
        /// Calls the given closure on each element in the sequence in the same order as a for-in loop.
        ///
        /// - Parameter body: A closure that takes an element of the sequence as a parameter.
        func forEach(_ body: (Element) -> Void) {
            queue.sync { self.array.forEach(body) }
        }
        
        /// Returns a Boolean value indicating whether the sequence contains an element that satisfies the given predicate.
        ///
        /// - Parameter predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value that indicates whether the passed element represents a match.
        /// - Returns: true if the sequence contains an element that satisfies predicate; otherwise, false.
        func contains(where predicate: (Element) -> Bool) -> Bool {
            var result = false
            queue.sync { result = self.array.contains(where: predicate) }
            return result
        }
    }
    
    // MARK: - Mutable
    public extension SynchronizedArray {
    
        /// Adds a new element at the end of the array.
        ///
        /// - Parameter element: The element to append to the array.
        func append( _ element: Element) {
            queue.async(flags: .barrier) {
                self.array.append(element)
            }
        }
    
        /// Adds a new element at the end of the array.
        ///
        /// - Parameter element: The element to append to the array.
        func append( _ elements: [Element]) {
            queue.async(flags: .barrier) {
                self.array += elements
            }
        }
    
        /// Inserts a new element at the specified position.
        ///
        /// - Parameters:
        ///   - element: The new element to insert into the array.
        ///   - index: The position at which to insert the new element.
        func insert( _ element: Element, at index: Int) {
            queue.async(flags: .barrier) {
                self.array.insert(element, at: index)
            }
        }
    
        /// Removes and returns the element at the specified position.
        ///
        /// - Parameters:
        ///   - index: The position of the element to remove.
        ///   - completion: The handler with the removed element.
        func remove(at index: Int, completion: ((Element) -> Void)? = nil) {
            queue.async(flags: .barrier) {
                let element = self.array.remove(at: index)
                
                DispatchQueue.main.async {
                    completion?(element)
                }
            }
        }
        
        /// Removes and returns the element at the specified position.
        ///
        /// - Parameters:
        ///   - predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element is a match.
        ///   - completion: The handler with the removed element.
        func remove(where predicate: @escaping (Element) -> Bool, completion: ((Element) -> Void)? = nil) {
            queue.async(flags: .barrier) {
                guard let index = self.array.index(where: predicate) else { return }
                let element = self.array.remove(at: index)
                
                DispatchQueue.main.async {
                    completion?(element)
                }
            }
        }
    
        /// Removes all elements from the array.
        ///
        /// - Parameter completion: The handler with the removed elements.
        func removeAll(completion: (([Element]) -> Void)? = nil) {
            queue.async(flags: .barrier) {
                let elements = self.array
                self.array.removeAll()
                
                DispatchQueue.main.async {
                    completion?(elements)
                }
            }
        }
    }
    
    public extension SynchronizedArray {
        
        /// Accesses the element at the specified position if it exists.
    	///
    	/// - Parameter index: The position of the element to access.
    	/// - Returns: optional element if it exists.
        subscript(index: Int) -> Element? {
            get {
                var result: Element?
                
                queue.sync {
                    guard self.array.startIndex..<self.array.endIndex ~= index else { return }
                    result = self.array[index]
                }
                
                return result
            }
            set {
                guard let newValue = newValue else { return }
                
                queue.async(flags: .barrier) {
                    self.array[index] = newValue
                }
            }
        }
    }
    
    
    // MARK: - Equatable
    public extension SynchronizedArray where Element: Equatable {
    
        /// Returns a Boolean value indicating whether the sequence contains the given element.
        ///
        /// - Parameter element: The element to find in the sequence.
        /// - Returns: true if the element was found in the sequence; otherwise, false.
        func contains(_ element: Element) -> Bool {
            var result = false
            queue.sync { result = self.array.contains(element) }
            return result
        }
    }
    
    // MARK: - Infix operators
    public extension SynchronizedArray {
    
        static func +=(left: inout SynchronizedArray, right: Element) {
            left.append(right)
        }
    
        static func +=(left: inout SynchronizedArray, right: [Element]) {
            left.append(right)
        }
    }
     
    // Thread-unsafe array
    do {
        var array = [Int]()
        var iterations = 1000
        let start = Date().timeIntervalSince1970
     
        DispatchQueue.concurrentPerform(iterations: iterations) { index in
            let last = array.last ?? 0
            array.append(last + 1)
    	
    	DispatchQueue.global().sync {
                iterations -= 1
            
                // Final loop
                guard iterations <= 0 else { return }
                let message = String(format: "Unsafe loop took %.3f seconds, count: %d.",
                    Date().timeIntervalSince1970 - start,
                    array.count
    	    )
                print(message)
    	}
        }
    }
     
    // Thread-safe array
    do {
        var array = SynchronizedArray<Int>()
        var iterations = 1000
        let start = Date().timeIntervalSince1970
     
        DispatchQueue.concurrentPerform(iterations: iterations) { index in
            let last = array.last ?? 0
            array.append(last + 1)
            
    	DispatchQueue.global().sync {
    		iterations -= 1
            
    	        // Final loop
            	guard iterations <= 0 else { return }
    	        let message = String(format: "Safe loop took %.3f seconds, count: %d.",
            	    Date().timeIntervalSince1970 - start,
    	            array.count)
            	print(message)
    	}
        }
    }
     
    PlaygroundPage.current.needsIndefiniteExecution = true
    
    

    external by tkhoa2711  2470  137  4  0

    A thread-safe implementation of Singleton in Python

    A thread-safe implementation of Singleton in Python: Singleton.py
    import threading
    
    # A thread-safe implementation of Singleton pattern
    # To be used as mixin or base class
    class Singleton(object):
        
        # use special name mangling for private class-level lock
        # we don't want a global lock for all the classes that use Singleton
        # each class should have its own lock to reduce locking contention
        __lock = threading.Lock()
        
        # private class instance may not necessarily need name-mangling
        __instance = None
        
        @classmethod
        def instance(cls):
            if not cls.__instance:
                with cls.__lock:
                    if not cls.__instance:
                        cls.__instance = cls()
            return cls.__instance
    
    
    • Public Snippets
    • Channels Snippets