logo
down
shadow

New to threads : problems using std::ref() in thread parameters


New to threads : problems using std::ref() in thread parameters

By : Syd Luce
Date : November 21 2020, 07:38 AM
This might help you I am new to C++ threads and trying make several objects packed in a std::vector call their prepareForRendering(...) method asynchronously. It seems I am using std::ref wrongly. This works : , Just pass pointer to bind:
code :
std::thread t(&ObjMesh::prepareForRendering, &mesh, pDevice, prepareTextures, prepareVertices, prepareBuffers, filter, addressMode);


Share : facebook icon twitter icon
Java - Two threads communicating via wait()/notify() but threads are alternating on with thread gets lock first

Java - Two threads communicating via wait()/notify() but threads are alternating on with thread gets lock first


By : xiaoA
Date : March 29 2020, 07:55 AM
wish helps you The desired output of this programme is: , This
code :
    Printer printer = new Printer(6);
    PingPongThread pingThread = new PingPongThread(printer, "Ping");
    synchronized (printer) {
        printer.wait();
    }
    PingPongThread pongThread = new PingPongThread(printer, "Pong");
final Object obj = new Object();
Thread t1 = new Thread() {
    public void run() {
        synchronized (obj) {
            obj.notify();
        }
    };
};

Thread t2 = new Thread() {
    public void run() {
        synchronized (obj) {
            try {
                obj.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };
};

t1.start();
t2.start();
Is it possible to have a set of thread pools that share threads from a large thread pool instead of creating new thread?

Is it possible to have a set of thread pools that share threads from a large thread pool instead of creating new thread?


By : user3642905
Date : March 29 2020, 07:55 AM
this one helps. Instead of thread pools, think of executors. An executor consists of 2 things: a job queue and a thread pool. What you need is a light-weight executor for each request which has a job queue but has no threads. Instead, it passes jobs from its queue to the main executor (which owns all the threads). The trick is that the light-weight executor counts how many jobs it has submitted to the main executor, and stops passing jobs when the number exceeds the limit. Each job, before being passed to the main executor, is wrapped in an object of type Runnable which a) has the reference to the parent light-weight executor, b) executes the wrapped job and c) notifies the referenced executor when the job is finished so that the executor can pass another job to the main executor (or just decrease the job counter, if there is no jobs in the queue).
2 Threads, Irc connection on second thread, want first thread to tell thread to send a message

2 Threads, Irc connection on second thread, want first thread to tell thread to send a message


By : MusicandSoul Georgin
Date : March 29 2020, 07:55 AM
it fixes the issue I was alredy able to achieve what I was looking for. I used global variables.
When I run several threads that match the number of CPU core/threads, will each thread run on a separate core/thread?

When I run several threads that match the number of CPU core/threads, will each thread run on a separate core/thread?


By : youre.pena
Date : March 29 2020, 07:55 AM
Any of those help The standard does not guarantee anything about on what cores/hyperthreads your threads will run. That is up to the operating system.
If you want to get platform specific (non-portable) then there are various API's to control thread affinity - like (for example) pthread_setaffinity_np on Linux. But I'd personally advice just leaving it to the OS - it will most likely do a good job unless you have very specific needs.
More than 2 threads working slower than 1 or 2 threads unless Thread.sleep(1) is put in the run() method of a thread

More than 2 threads working slower than 1 or 2 threads unless Thread.sleep(1) is put in the run() method of a thread


By : user2706381
Date : March 29 2020, 07:55 AM
hop of those help? You are not waiting for your tasks to complete, only measuring the time it takes to submit them to the executor.
executor.shutdown() does not wait for all tasks get finished.You need to call executor.awaitTermination after that.
code :
executor.shutdown();
executor.awaitTermination(5, TimeUnit.HOURS);
Benchmark                  Mode  Cnt    Score    Error  Units
SpeedTest.multipleThreads  avgt   20  559.996 ± 20.181  ms/op
SpeedTest.singleThread     avgt   20  562.048 ± 16.418  ms/op
public class ParallelCollatz implements Callable<Long> {

    private final long inputNumInit;

    public ParallelCollatz(long inputNumInit) {
        this.inputNumInit = inputNumInit;
    }


    @Override
    public Long call() {
        long result = 1;
        long inputNum = inputNumInit;
        //main recursive computation
        while (inputNum > 1) {

            if (inputNum % 2 == 0) {
                inputNum = inputNum / 2;
            } else {
                inputNum = inputNum * 3 + 1;
            }
            ++result;
        }
        return result;
    }

}
@State(Scope.Benchmark)
public class SpeedTest {
private static final int NUM_TASKS = 1000000;

    private static List<ParallelCollatz> tasks = buildTasks();

    @Benchmark
    @Fork(value = 1, warmups = 1)
    @BenchmarkMode(Mode.AverageTime)
    @OutputTimeUnit(TimeUnit.MILLISECONDS)
    @SuppressWarnings("unused")
    public long singleThread() throws Exception {
        ThreadPoolExecutor executorOneThread = (ThreadPoolExecutor) Executors.newFixedThreadPool(1);
        return measureTasks(executorOneThread, tasks);
    }

    @Benchmark
    @Fork(value = 1, warmups = 1)
    @BenchmarkMode(Mode.AverageTime)
    @OutputTimeUnit(TimeUnit.MILLISECONDS)
    @SuppressWarnings("unused")
    public long multipleThreads() throws Exception {
        ThreadPoolExecutor executorMultipleThread = (ThreadPoolExecutor) Executors.newFixedThreadPool(4);
        return measureTasks(executorMultipleThread, tasks);
    }

    private static long measureTasks(ThreadPoolExecutor executor, List<ParallelCollatz> tasks) throws InterruptedException, ExecutionException {
        long sum = runTasksInExecutor(executor, tasks);
       return sum;
    }

    private static long runTasksInExecutor(ThreadPoolExecutor executor, List<ParallelCollatz> tasks) throws InterruptedException, ExecutionException {
        List<Future<Long>> futures = new ArrayList<>(NUM_TASKS);
        for (int i = 0; i < NUM_TASKS; i++) {
            Future<Long> f = executor.submit(tasks.get(i));
            futures.add(f);
        }
        executor.shutdown();

        boolean tempFirst = false;
        try {
            tempFirst = executor.awaitTermination(5, TimeUnit.HOURS);
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        long sum = 0l;
        for (Future<Long> f : futures) {
            sum += f.get();
        }
        //System.out.println(sum);
        return sum;
    }

    private static List<ParallelCollatz> buildTasks() {
        List<ParallelCollatz> tasks = new ArrayList<>();
        for (int i = 1; i <= NUM_TASKS; i++) {
            ParallelCollatz task = new ParallelCollatz((long) (i + NUM_TASKS));

            tasks.add(task);

        }
        return tasks;
    }

}
Related Posts Related Posts :
  • Complexity analysis of loop with limited looping time
  • Boost test fails with enum classes inside namespaces
  • is this a function declaration?
  • Socket recv() one byte at a time
  • C++ Glibc Detected error. Double Free or corruption
  • OpenCV - How to write IplImage array in Mat form?
  • Qt event when anything changed on the window/screen + Screenshot
  • OpenGL Linker error, linking with uncompiled shader
  • Find 4 specific corner pixels and use them with warp perspective
  • Cin Execution Not Working (program.exe < filewithdata.txt)
  • cudaMallocManaged causes Access Violation
  • How to correctly read a value from stdin into a variable
  • Binary Search Tree Forgetting Every Node I Add
  • C++ Return Value from function not same as that value in function
  • Microsoft Visual Studio C++, OpenCV animation
  • C++ function pointer syntax. Why does (*) work but * not?
  • C++: Template class binary operator overloading - seg fault?
  • Passing buffer between two terminals (Named Pipe)
  • C++ parse sub-string to integer
  • Create stereo context for modern opengl
  • Memory leak, when using GLM
  • Get Control under cursor
  • Is this proper behavior? std::map iterator invalidation
  • 2D isometric engine - Math problems - Cube selection - diamond shape map
  • Open second window in Qt
  • Stack Overflow error with Vectors
  • Pure Virtual Friend Class
  • Object initialization syntax in C++
  • Variable undefined error
  • C++ tolower/toupper char pointer
  • Overhead with std::function
  • Is there a way to make a loop that get user input but doesn't stop if the user doesn't input anything?
  • OpenCV in cmake-based project: checking for contrib modules
  • shared_ptr vs unique_ptr uses in classes and children
  • MFC dialog Border padding changed after switching from VS2010 to 2012 or later
  • String rotator in C++ (bitwise rotation)
  • Custom sort vector of pair based on their values
  • Pointer to const overloaded member function
  • how to avoid this for-loop mess in c++?
  • Can the state of a standard C++ iostream manipulator be polled?
  • How to make sure a data type is as large as it needs to be in C++
  • Why is my first ofstream output in my else block missing the fill character?
  • Returning static/ normal arrays in recursion/another function
  • c++, why use const std::string & parameterName?
  • expression did not evaluate to a constant in C++ VS
  • Owner object that takes pre-created values ? Wrong design?
  • Cannot use Macro in a C++ constructor?
  • vector is loosing mat4 information
  • Invalid declarator before with map of struct?
  • std::initializer_list to return member variables returns incorrect values
  • Unable to use Boost + Qt in Mac
  • Passing template function and overload as function argument
  • non standard extension warning when searching in a vector of unique_ptrs
  • Qt Windows x64 build succeeds in IDE but not on the command line
  • condition_variable::wait_for method not returning - even after the timeout
  • boost::asio usage in self-contained class
  • CGAL triangulation with constraints changes points coords
  • How to resolve an ambiguous reference caused by a conflicting identifier from inline namespace
  • When UTF8 emoji character is removed from NSMutableString the conversion to std::string fails
  • XOR of two strings of 0s and 1s
  • shadow
    Privacy Policy - Terms - Contact Us © animezone.co