[tl] Thread Custom Fields Links

Description: Make a connection between threads.

Options:

  • Thread field IDs: Custom fields IDs which contain thread links for parsing

Permissions:
How it’s work?

Example a threadA you have put links to threadB, threadC and threadD. Then in the threadB, threadC, and threadC will display a link to threadA.

.

python – Have I implemented thread safety for this cache?

I’ve written a simple LRU cache class and I am trying to make it thread-safe. My thoughts are that I just need to wrap the code that updates the ordered dict in a lock so that if any thread is writing to the ordered dict, all other writes/reads need to wait. Is that correct?

Also, what is the best way to test that something is thread-safe?

import threading
from collections import OrderedDict

class Cache:
  def __init__(self, capacity):
    self._count = 0
    self._capacity = capacity
    self._store = OrderedDict()
    self._lock = threading.Lock()
    
  def count(self):
    return self._count

  def capacity(self):
    return self._capacity

  def get(self, key):
    if key in self._store:
      self._store.move_to_end(key)
    return self._store(key)

  def set(self, key, value):
    with self._lock: # this was the only place i thought that needed locking
      if key not in self._store:
        if self._count >= self._capacity:
          self._store.popitem(last=False)
          self._count -= 1
        self._store(key) = value
        self._count += 1
      else:
        self._store(key) = value
        self._store.move_to_end(key)

  def containsKey(self, key):
    return key in self._store
```

KOTLIN – As operações de longa duração devem ser executadas em threads de fundo e as operações relacionDAsa visão na thread principal

inserir a descrição da imagem aquiclass Presenter(view: ListContract.View, elementsProvider: ElementsProvider, schedulerFacade: SchedulerFacade) {
val disposables = CompositeDisposable()

init {
disposables.add(
elementsProvider.loadElements()
.subscribeOn(schedulerFacade.background)
.observeOn(schedulerFacade.main)
.subscribe()
)
}
}

python 3.x – Start and kill thread on given pid

I have been working on I/O Bound application where I want to learn how I can kill a thread on given PID, by PID I mean a specific URL I want to kill as I later on will do an API or listen to a stream file which will tell me which PID to kill in the future. Before I am coming to that part I would see if I am able to do a kill thread before I implement a API/Listen to a stream function.

I have created this code:

import sys
import threading
import time

import requests

store_pids = {}

URLS = (
    "https://www.bbc.co.uk/",
    "https://www.sydsvenskan.se/",
    "https://news.google.com/",
    "https://www.nbcnews.com/"
)


class MyThread(threading.Thread):
    def __init__(self, *args, **keywords):
        threading.Thread.__init__(self, *args, **keywords)
        self.killed = False

    def start(self):
        self.__run_backup = self.run
        self.run = self.__run
        threading.Thread.start(self)

    def __run(self):
        sys.settrace(self.globaltrace)
        self.__run_backup()
        self.run = self.__run_backup

    def globaltrace(self, frame, event, arg):
        if event == 'call':
            return self.localtrace
        else:
            return None

    def localtrace(self, frame, event, arg):
        if self.killed:
            if event == 'line':
                raise SystemExit()
        return self.localtrace

    def kill(self):
        self.killed = True


def each_url(given_url):
    while True:
        # Webcrawling site to check for new news coming
        rep = requests.get(given_url)
        print(f"Request status code: {rep.status_code} -> URL: {given_url}nSleep 3 sec")
        time.sleep(3)


if __name__ == '__main__':

    for url in URLS:
        store_pids(url) = MyThread(target=each_url, args=(url,))
        store_pids(url).start()

    # Check if we actually have killed the process
    print("---------------")
    print(f"Wait 10 seconds before terminating: Current threads running:")
    for thread in threading.enumerate():
        for key, value in store_pids.items():
            if thread == value:
                print(key, value)
    print("---------------")

    # Sleep 10 seconds
    time.sleep(10)

    # Kill specific URL
    print("Killing https://www.sydsvenskan.se/....")
    store_pids("https://www.sydsvenskan.se/").kill()
    store_pids("https://www.sydsvenskan.se/").join()
    del store_pids("https://www.sydsvenskan.se/")

    # Check if its killed
    print("---------------")
    print(f"Current threads running after the kill")
    for thread in threading.enumerate():
        for key, value in store_pids.items():
            if thread == value:
                print(key, value)
    print("---------------")

It does seem to work as I want to where it actually kills the specific thread but I wonder what can I do to even improve this code even more! 🙂

Looking forward!

Quando executo meu código aparece o seguinte erro Exception in thread "main" java.lang.NullPointerException

package ui;

import javax.swing.*;

public class MainForm extends JFrame {
private JPanel rootPanel;
private JButton buttonNewContact;
private JButton buttonRemove;
private JTable tableContacts;

   public MainForm() {
          setContentPane(rootPanel);
          setSize(500,300);
          setVisible(true);

   }

   private void createUIComponents() {
          // TODO: place custom component creation code here


   }

}

[cXF] Thread prefix icons | NulledTeam UnderGround

Would you like to customize your prefixes?

Here’s a simple DIY tutorial as an example. Of course you can extended it for your own needs as you wish.

So, read this tutorial to achieve something like this:

194664

1. Create your custom prefix

In admin CP go to Forums > Thread prefixes and click on button Add prefix on the right top side.

Fill the form like this:

[IMG…

.

LibGDX – Actors added to a stage from a network thread are not drawn

I have an application with several Screen and Actor. On my main screen, the actors added to the stage during creation are rendering fine.

However, I have a Netty server running, and when it receive certain events, it adds, in the network thread, new actors to the stage. These are never drawn, despite the main thread continuing to call the render function of the corresponding screen.

In the code below, if I call recieveInbound from the Screen’s show by mocking the exact same network payload, the actors are drawn as expected.

What am I doing wrong?

MainScreen.java

// ...

public MainScreen(Game game) {
    batch = game.getBatch();
    viewport = game.getMainViewport();
    stage = new Stage(viewport, batch);

    try {
        capabilities = GL.getCapabilities();
    }
    catch (IllegalStateException e) {
        capabilities = GL.createCapabilities();
    }
}

/**
 * Receives and manages signals from the remotes.
 *
 * @param code The received code
 * @param object The received payload
 */
public void receiveInbound(int code, Object object) {

    // Restore OpenGL context if needed before processing.
    try {
        GL.getCapabilities();
    }
    catch (IllegalStateException e) {
        GL.setCapabilities(capabilities);
    }
    // LOGGER.debug(stage.getActors().size); <-- 1 added in show, as expected
    if (code == 10) {
        LevelMap map = mapManager.serve(code, object);
        stage.addActor(map.getBackground());
        Arrays.stream(map.contentMatrix)
            .forEach(row -> Arrays.stream(row)
                .forEach(stage::addActor)
            );
    }
    // LOGGER.debug(stage.getActors().size); <-- 854, as expected
}

@Override
public void render(float delta) {
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL33.GL_COLOR_BUFFER_BIT);
    batch.setProjectionMatrix(viewport.getCamera().combined);
    // Expected position, actors are around there.
    viewport.getCamera().position.set(0,0,0); 
    stage.act();
    stage.draw();
}

c++ – Is this thread pool implementation OK?

There are things that I am not 100% sure.
Is it possible that dangling references can be create in add_task method?
Is it possible that this implementation will deadlock?
I had to use shared_ptr in order to store packaged_task in the queue. Is there a better way to do it?

class ThreadPool {
public:
    ThreadPool(int number_of_workers) {
        for (int i=0; i<number_of_workers; ++i) {
            worker_threads.push_back(std::thread{std::bind(&ThreadPool::thread_func, this)});
        }
    }
    
    ~ThreadPool() = default;
    
    ThreadPool(const ThreadPool&) = delete;
    ThreadPool(ThreadPool&&) = delete;
    ThreadPool& operator=(const ThreadPool&) = delete;
    ThreadPool& operator=(ThreadPool&&) = delete;
    
    template<typename Func, typename... Args>
    decltype(auto) add_task(Func&& func, Args... args) {
        using ReturnType = decltype(func(args...));
        auto ptask = std::make_shared<std::packaged_task<ReturnType()>>(
            std::bind(std::forward<Func>(func), std::forward<Args>(args)...));
        auto fut = ptask->get_future();
        {
            std::unique_lock lk{pool_mutex};
            task_queue.push((pt = std::move(ptask))() { (*pt)(); });
        }
        cond.notify_one();
        return fut;
    }

    void stop() {
        {
            std::unique_lock lk{pool_mutex};
            stopped = true;
        }
        cond.notify_all();
        for (auto& th : worker_threads) {
            if (th.joinable()) {
                th.join();
            }
        }
    }

private:
    void thread_func() {
        while(true) {
            std::unique_lock lk{pool_mutex};
            if (task_queue.empty() && stopped) {
                break;
            }

            if (task_queue.empty()) {
                cond.wait(lk, (this)() { return !task_queue.empty() || stopped; });
            }

            if (!task_queue.empty()) {
                auto callable = std::move(task_queue.front());
                task_queue.pop();
                lk.unlock();
                callable();
            }
            else if (stopped) {
                break;
            }
        }
    }

private:
    std::mutex pool_mutex;
    std::vector<std::thread> worker_threads;
    bool stopped = false;
    std::condition_variable cond;
    std::queue<std::function<void()>> task_queue;
};

Note, that add_task returns a future that can be used to wait for a specific task to complete.

google sheets – Only the first thread is displayed in my Apps Scripts program, but I need all the threads

My issue is that the first thread in my inbox is being displayed 45 times which is the number of messages in my inbox. What I need is the for loop to go through all the threads and gather all the information in the threads into a 2D array.

I know the issue is most likely with var message = threads(i).getMessages()(0) but I’m not sure how to solve the problem.

This my code:

function TheaThreads(){
    var SS =SpreadsheetApp.getActiveSpreadsheet();
    var ThreadSheet = SS.getSheetByName("Threads");
    var threads = GmailApp.getInboxThreads();
  for (var i=0; i < threads.length; i++) {
    var message = threads(i).getMessages()(0),
    label = threads(i).getLabels(),
    //subject = message.getSubject(),
    //content = message.getPlainBody(),
    ident = message.getId(),
    emailfrom = message.getFrom();

  if(label==null|| label== undefined|| label.length==0){
    label="No Label";
  }

  var threadArray = new Array();
  for(i=0; i<threads.length; i++){
    threadArray(i) = new Array();
    threadArray(i)(0)= ident;
    threadArray(i)(1)= label;
    threadArray(i)(2)= emailfrom;

    Logger.log(threadArray);
    }
   }