libdispatch dispatch semaphore vs. serial dispatch queue

Status
Not open for further replies.

Mark Cianciosa

Wise, Aged Ars Veteran
161
I have a code that is calculating coulomb interactions F = q1*q2/(c*r^2) it effectively looks like this.
Code:
for (size_t i = 0, e = numParticles - 1; i < e; i++) {
    for (size_t j = i + 1; j < numParticles;  j++) {
        ... Calculate magnetude of force ...
        
        force[i] += forceMagnetude;
        force[j] -= forceMagnetude;
    }
}
I currently have this parallelized as
Code:
dispatch_apply(numParticles - 1, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0) ^(size_t i) {
    for (size_t j = i + 1; j < numParticles;  j++) {
        ... Calculate magnetude of force ...
        
        dispatch_semaphore_wait(sema[i], DISPATCH_TIME_FOREVER);
        force[i] += forceMagnetude;
        dispatch_semaphore_signal(sema[i]);

        dispatch_semaphore_wait(sema[j], DISPATCH_TIME_FOREVER);
        force[j] -= forceMagnetude;
        dispatch_semaphore_signal(sema[j]);
    }
});
but this could also be written as
Code:
dispatch_apply(numParticles - 1, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0) ^(size_t i) {
    for (size_t j = i + 1; j < numParticles;  j++) {
        ... Calculate magnetude of force ...
        
        dispatch_sync(serial_queue[i], ^{
            force[i] += forceMagnetude;
        });
        
        dispatch_sync(serial_queue[j], ^{
            force[j] -= forceMagnetude;
        });
    }
});
These two methods effectively perform the function, making sure force is updated atomically. Which of these two methods is better? Which one would be faster and make the most efficient use of all cores? Note the actual code is question is using __m128d vectors so it's not quite as simple as replacing += with an atomic operation.

I have a second snippet of code that looks like
Code:
dispatch_apply(numParticles, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0) ^(size_t i) {
    ...do work...

    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    non_threadsafe_function();
    dispatch_semaphore_signal(sema);

    ...do more work...
});
is it better to write this as
Code:
dispatch_apply(numParticles, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0) ^(size_t i) {
    ...do work...

    dispatch_sync(serial_queue, ^{
        non_threadsafe_function();
    })

    ...do more work...
});
 

Mark Cianciosa

Wise, Aged Ars Veteran
161
Benchmarks so far. On the first code example, the nested for loops.
Test machine. Dual core running 10.6.6
Number of particles 1000
Simulation time 5s

dispatch_semaphore:
Execution Time: ~6min 57s ±1s
CPU utilization ~195%

serial queue:
Execution Time: ~7min 12s ±1s
CPU utilization ~191%

This is what I was expecting since dispatch_semaphore are light weight and chances of two threads hitting the same semaphore is rare since I'm using a unique semaphore object for each particle.
 

Mark Cianciosa

Wise, Aged Ars Veteran
161
DrPizza":3hoj35iw said:
15 seconds in 7 minutes is not really a meaningful difference (3.6%), IMO.
I would agree except for that section of code scales like O(n^2), so that 3% will become greater with a larger number of particles.

More surprising however was when I turned on the second code scenario.

dispatch_semaphore:
Execution Time: ~8min 11s ±1s
CPU utilization ~195%

serial queue:
Execution Time: ~21min 0s ±1s
CPU utilization ~145%
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
so that 3% will become greater with a larger number of particles.

I wouldn't say that's a given. The contention may actually reduce as the number of particles increases.

I would have thought it would have some effect on scaling as cpu cores are increased, but I'd not bet on anything without running the numbers...
 

Mark Cianciosa

Wise, Aged Ars Veteran
161
CFM":1fwub78p said:
One thing to look into is block copying overhead. You can either pre-copy blocks or use dispatch_async_f to avoid it if it's causing issues.
I'm not using dispatch_async anywhere. dispatch_apply and dispatch_sync don't perform a Block_copy because the parent function never goes out of scope before they finish. These functions never need to copy a block from the stack to the heap.

I believe the semaphores are so much faster because they only need to block a thread when the count is zero where as dispatch_sync always has to block the calling thread. From the libdispatch source code, the semaphore functions are essentially.
Code:
dispatch_semaphore_wait(...) {
    if (--count >= 0)
        return; // Fast path
    
    block_calling_thread(); // Slow path
}

dispatch_semaphore_signal(...) {
    if (++count > 0)
        return; // Fast path

    unblock_blocked_thread(); // Slow path
}
I think in the two examples especially the first case that a thread calling dispatch_semaphore_wait when the count is zero is very rare so it's usually taking the fast path and rarely blocking the calling thread. A dispatch_sync function, on the other hand, always has to block the calling thread until the block completes.
 
I think in the two examples especially the first case that a thread calling dispatch_semaphore_wait when the count is zero is very rare so it's usually taking the fast path and rarely blocking the calling thread. A dispatch_sync function, on the other hand, always has to block the calling thread until the block completes.
Not sure what you mean by that; the semaphore method also has to block the thread until the guarded code (analogous to the block) completes, too.
 

Mark Cianciosa

Wise, Aged Ars Veteran
161
DrPizza":242r9u7u said:
Not sure what you mean by that; the semaphore method also has to block the thread until the guarded code (analogous to the block) completes, too.

Image thread A and thread B. You can have two sequences of events.

Semaphore Count = 1
Thread A hits semaphore wait
Semaphore Count = 0
Thread A does work.
Thread A hits semaphore signal
Semaphore Count = 1
Thread B hits semaphore wait
Semaphore Count = 0
Thread B does work.
Thread B hits semaphore signal
Semaphore Count = 1

or

Semaphore Count = 1
Thread A hits semaphore wait
Semaphore Count = 0
Thread B hits semaphore wait
Semaphore Count = -1 => Causes thread B to stop
Thread A does work.
Thread A hits semaphore signal
Semaphore Count = 0 => Causes thread B to wake up
Thread B does work.
Thread B hits semaphore signal
Semaphore Count = 1

In the best case, neither thread ever has to halt. In the worse case, one thread has to halt. I think in my code it's very rare that a thread is hitting a semaphore when the count is 0.

For the serial queue method.

Thread A hits dispatch_sync
Block is added to serial queue.
Thread A stops while thread C executes.
Block added from A completes.
Thread A wakes up.
Thread B hits dispatch_sync
Block is added to serial queue.
Thread B stops while thread C executes.
Block added from B completes.
Thread B wakes up.

or

Thread A hits dispatch_sync
Block is added to serial queue.
Thread B hits dispatch_sync
Block is added to serial queue.
Thread A stops while thread C executes.
Thread B stops while thread C executes.
Block added from A completes.
Thread A wakes up.
Block added from B completes.
Thread B wakes up.

In the best case one thread has to halt. In the worse case both threads have to halt while serial queue executes. Then take into account there is more over head adding a block to a queue than there is in incrementing or decrementing an integer.
 
In the best case one thread has to halt. In the worse case both threads have to halt while serial queue executes. Then take into account there is more over head adding a block to a queue than there is in incrementing or decrementing an integer.
What? Why? I don't understand at all. Why does any thread have to halt? Except in unusual circumstances dispatch_sync is executed on the current thread, and if you were subject to those unusual circumstances you would need that specific behaviour, so the semaphore version would not be equivalent anyway.

The unusual circumstance is when blocks are submitted to the main thread. The main thread is special and blessed, and so if you dispatch_sync to the main thread it does indeed wait for the main thread to run the block before allowing the submitting block to finish. But like I say if you need this behaviour, your alternative solution doesn't work anyway. See here.

Blocks in GCD have no thread affinity; only the main thread is special in this way.
 

Mark Cianciosa

Wise, Aged Ars Veteran
161
DrPizza":3e2dbp43 said:
In the best case one thread has to halt. In the worse case both threads have to halt while serial queue executes. Then take into account there is more over head adding a block to a queue than there is in incrementing or decrementing an integer.
What? Why? I don't understand at all. Why does any thread have to halt? Except in unusual circumstances dispatch_sync is executed on the current thread, and if you were subject to those unusual circumstances you would need that specific behaviour, so the semaphore version would not be equivalent anyway.
They both prevent a race condition how are they not equivalent? Replace every where I said threads with blocks in the global queue. Blocks in one queue have to stop, be dequeued, wait for a block on the serial queue to finish. In the semaphore case it doesn't. It has the same effect.

The unusual circumstance is when blocks are submitted to the main thread. The main thread is special and blessed, and so if you dispatch_sync to the main thread it does indeed wait for the main thread to run the block before allowing the submitting block to finish. But like I say if you need this behaviour, your alternative solution doesn't work anyway. See here.
That function isn't used anywhere.
 
Mark Cianciosa":1sq1nn0e said:
DrPizza":1sq1nn0e said:
In the best case one thread has to halt. In the worse case both threads have to halt while serial queue executes. Then take into account there is more over head adding a block to a queue than there is in incrementing or decrementing an integer.
What? Why? I don't understand at all. Why does any thread have to halt? Except in unusual circumstances dispatch_sync is executed on the current thread, and if you were subject to those unusual circumstances you would need that specific behaviour, so the semaphore version would not be equivalent anyway.
They both prevent a race condition how are they not equivalent? Replace every where I said threads with blocks in the global queue. Blocks in one queue have to stop, be dequeued, wait for a block on the serial queue to finish.
Only in the contended case.

In the semaphore case it doesn't. It has the same effect.
There's more to the main thread than avoiding race conditions; it's there to avoid cross-threaded GUI calls. That's why it's special-cased.

The unusual circumstance is when blocks are submitted to the main thread. The main thread is special and blessed, and so if you dispatch_sync to the main thread it does indeed wait for the main thread to run the block before allowing the submitting block to finish. But like I say if you need this behaviour, your alternative solution doesn't work anyway. See here.
That function isn't used anywhere.
Oops, I alt-tabbed back to the window and must have read the wrong line; I think I meant to link to this one. In the blocking case it does put an entry on the queue to be performed by another thread but, unless the target queue is the other thread, that entry is just there to suspend the queue (to ensure that nothing new can be inserted by any other threads) and release the semaphore so that execution of the block can occur on the original thread.

But if you don't want to trace through the source yourself and verify that dispatch_sync executes on the same thread unless dispatching to the main thread, just print out the thread id before the call to dispatch_sync and again within the block. You'll see for yourself that the thread ID doesn't change.
 
Code:
#include <cstdio>
#include <dispatch/dispatch.h>

const size_t NUM_PARTICLES = 10;
dispatch_queue_t serial_queues[NUM_PARTICLES]; // global to avoid whining that I can't pass it to a block. I think the other option is to put it inside a struct.

int main()
{
	dispatch_apply(NUM_PARTICLES, dispatch_get_global_queue(0, 0), ^(size_t i) {
		serial_queues[i] = dispatch_queue_create(NULL, NULL);
	});
	
	dispatch_apply(NUM_PARTICLES - 1, dispatch_get_global_queue(0, 0), ^(size_t i) {
		for(size_t j = i + 1; j < NUM_PARTICLES; ++j)
		{
			pthread_t parallel_thread = pthread_self();
			dispatch_sync(serial_queues[i], ^{
				pthread_t serial_thread = pthread_self();
				printf("My parallel thread was %p but I'm now in %p\n", parallel_thread, serial_thread);
			});
		}
	});
}

Produces e.g.:
Code:
My parallel thread was 0x1000b6000 but I'm now in 0x1000b6000
My parallel thread was 0x7fff70c5eca0 but I'm now in 0x7fff70c5eca0
My parallel thread was 0x1000b6000 but I'm now in 0x1000b6000
My parallel thread was 0x7fff70c5eca0 but I'm now in 0x7fff70c5eca0
My parallel thread was 0x1000b6000 but I'm now in 0x1000b6000
My parallel thread was 0x7fff70c5eca0 but I'm now in 0x7fff70c5eca0
My parallel thread was 0x1000b6000 but I'm now in 0x1000b6000
My parallel thread was 0x7fff70c5eca0 but I'm now in 0x7fff70c5eca0
My parallel thread was 0x1000b6000 but I'm now in 0x1000b6000
My parallel thread was 0x7fff70c5eca0 but I'm now in 0x7fff70c5eca0
My parallel thread was 0x1000b6000 but I'm now in 0x1000b6000
My parallel thread was 0x7fff70c5eca0 but I'm now in 0x7fff70c5eca0
My parallel thread was 0x1000b6000 but I'm now in 0x1000b6000
My parallel thread was 0x7fff70c5eca0 but I'm now in 0x7fff70c5eca0
My parallel thread was 0x1000b6000 but I'm now in 0x1000b6000
My parallel thread was 0x7fff70c5eca0 but I'm now in 0x7fff70c5eca0
My parallel thread was 0x1000b6000 but I'm now in 0x1000b6000
My parallel thread was 0x7fff70c5eca0 but I'm now in 0x7fff70c5eca0
My parallel thread was 0x1000b6000 but I'm now in 0x1000b6000
My parallel thread was 0x7fff70c5eca0 but I'm now in 0x7fff70c5eca0
My parallel thread was 0x1000b6000 but I'm now in 0x1000b6000
My parallel thread was 0x7fff70c5eca0 but I'm now in 0x7fff70c5eca0
My parallel thread was 0x1000b6000 but I'm now in 0x1000b6000
My parallel thread was 0x7fff70c5eca0 but I'm now in 0x7fff70c5eca0
My parallel thread was 0x1000b6000 but I'm now in 0x1000b6000
My parallel thread was 0x7fff70c5eca0 but I'm now in 0x7fff70c5eca0
My parallel thread was 0x1000b6000 but I'm now in 0x1000b6000
My parallel thread was 0x7fff70c5eca0 but I'm now in 0x7fff70c5eca0
My parallel thread was 0x1000b6000 but I'm now in 0x1000b6000
My parallel thread was 0x7fff70c5eca0 but I'm now in 0x7fff70c5eca0
My parallel thread was 0x1000b6000 but I'm now in 0x1000b6000
My parallel thread was 0x7fff70c5eca0 but I'm now in 0x7fff70c5eca0
My parallel thread was 0x1000b6000 but I'm now in 0x1000b6000
My parallel thread was 0x7fff70c5eca0 but I'm now in 0x7fff70c5eca0
My parallel thread was 0x1000b6000 but I'm now in 0x1000b6000
My parallel thread was 0x7fff70c5eca0 but I'm now in 0x7fff70c5eca0
My parallel thread was 0x1000b6000 but I'm now in 0x1000b6000
My parallel thread was 0x7fff70c5eca0 but I'm now in 0x7fff70c5eca0
My parallel thread was 0x1000b6000 but I'm now in 0x1000b6000
My parallel thread was 0x7fff70c5eca0 but I'm now in 0x7fff70c5eca0
My parallel thread was 0x1000b6000 but I'm now in 0x1000b6000
My parallel thread was 0x7fff70c5eca0 but I'm now in 0x7fff70c5eca0
My parallel thread was 0x1000b6000 but I'm now in 0x1000b6000
My parallel thread was 0x7fff70c5eca0 but I'm now in 0x7fff70c5eca0
My parallel thread was 0x1000b6000 but I'm now in 0x1000b6000

The thread isn't changing between the (parallel) caller and the (sync) inner. There is no "thread C".
 

Mark Cianciosa

Wise, Aged Ars Veteran
161
DrPizza":2ydg36q9 said:
Only in the contended case.
Which I'm saying for my code turns out to be rare.
There's more to the main thread than avoiding race conditions; it's there to avoid cross-threaded GUI calls. That's why it's special-cased.
Which is irrelevant because I'm not using the main queue at all in this and never claimed that using a semaphore is equivalent to putting something synchronized on the main queue. It's obvious that one can't use semaphores in place of submitting a block to the main queue.
Oops, I alt-tabbed back to the window and must have read the wrong line; I think I meant to link to this one. In the blocking case it does put an entry on the queue to be performed by another thread but, unless the target queue is the other thread, that entry is just there to suspend the queue (to ensure that nothing new can be inserted by any other threads) and release the semaphore so that execution of the block can occur on the original thread.

But if you don't want to trace through the source yourself and verify that dispatch_sync executes on the same thread unless dispatching to the main thread, just print out the thread id before the call to dispatch_sync and again within the block. You'll see for yourself that the thread ID doesn't change.
I see that. I tend to think of queues as threads because of how Apple presents them in the debugger and in stack dumps. In the case of my code, where the contended case is rare, the over head of adding a synchronized block to a serial queue is more than the over head of using a semaphore. In the contended case I think the semaphore still wins here because the code I'm protecting runs so quickly. There is a second fast path inside the semaphore slow path, on line 193, so the calls down to the kernel, line 273, that make the slow path slow never get called. I would be willing to bet that if the code I was trying to protect took longer to run, then the serial queue method would become faster.

In the second code case I found a faster method than both the serial queue and the semaphore that I'm using now. Since the non thread safe function was a random number generator, I cache random numbers for the next time on a serial queue dispatched asynchronously. The code in question looks something like this.
Code:
dispatch_group_async(nextGroup, randQueue, ^{
    for (cloud_index i = 0; i < numParticles; i++)
        nextCache[i] = rand_number_generator();
});

dipatch_group_wait(previousGroup, DISPATCH_TIME_FOREVER); // Wait for the previously created random numbers to finish before suing them.
dispatch_apply(numParticles, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0) ^(size_t i) {
    ... do work ...
    force[i] += constant*previousCache[i];
});
 
Mark Cianciosa":3m00dfag said:
DrPizza":3m00dfag said:
Only in the contended case.
Which I'm saying for my code turns out to be rare.
Which I'm saying means that dispatch_async is going to incur minimal overhead relative to the semaphore, since it'll just execute the payload in the same thread. There is no thread C!

Which is irrelevant because I'm not using the main queue at all in this and never claimed that using a semaphore is equivalent to putting something synchronized on the main queue. It's obvious that one can't use semaphores in place of submitting a block to the main queue.
I wasn't saying you were: I was explaining the one circumstance in which dispatch_sync doesn't, in fact, execute on the same thread.

I see that. I tend to think of queues as threads because of how Apple presents them in the debugger and in stack dumps.
I would strongly recommend you think of them as nothing of the sort. They're not; they don't act like threads, they don't have any particular correspondence with threads, they're a completely different beast.

In the case of my code, where the contended case is rare, the over head of adding a synchronized block to a serial queue is more than the over head of using a semaphore.
Perhaps, but marginally so, especially since, as you say, it's rare.

In the contended case I think the semaphore still wins here because the code I'm protecting runs so quickly. There is a second fast path inside the semaphore slow path, on line 193, so the calls down to the kernel, line 273, that make the slow path slow never get called. I would be willing to bet that if the code I was trying to protect took longer to run, then the serial queue method would become faster.
Well, I don't think you need to dispatch_sync at all to the serial queues. dispatch_async would do the right thing--it'd still perform the same updates in the same order. It's just it's probably not worth the overhead in this case, because the block is so simple; memory allocation overhead would kill you. If the serialized parts were more complex, however, such that sticking a block on a queue is cheaper than running the serial part, I think it might produce better results.

How good do you need your random numbers to be?
 

Mark Cianciosa

Wise, Aged Ars Veteran
161
DrPizza":33cberds said:
I would strongly recommend you think of them as nothing of the sort. They're not; they don't act like threads, they don't have any particular correspondence with threads, they're a completely different beast.
They act close enough. Replace where I said thread with Queue. Queue A and Queue B have to stop while Queue C finishes.
Perhaps, but marginally so, especially since, as you say, it's rare.
Not marginal enough for me and since that scales as O(n^2) that gap will widen when the number of particles are 10000 or 20000. It definitely wasn't marginal in the second case.
Well, I don't think you need to dispatch_sync at all to the serial queues. dispatch_async would do the right thing--it'd still perform the same updates in the same order. It's just it's probably not worth the overhead in this case, because the block is so simple; memory allocation overhead would kill you. If the serialized parts were more complex, however, such that sticking a block on a queue is cheaper than running the serial part, I think it might produce better results.
An async queue wouldn't be worth it. I need the total force on a particle to be calculated before I can calculate the new velocity of a particle. Doing that on an async queue would mean I have to add an async queue to everywhere I calculate a force. Then before I could use the total force I would have to wait for the async queue to finish.
How good do you need your random numbers to be?
Uniformly distributed and subject to two constraints.
〈Lᵢ(t)〉 = 0
〈Lᵢ(t)Lᵣ(t')〉 = δᵢᵣδ(t - t')
 
Mark Cianciosa":2qkwfvie said:
DrPizza":2qkwfvie said:
I would strongly recommend you think of them as nothing of the sort. They're not; they don't act like threads, they don't have any particular correspondence with threads, they're a completely different beast.
They act close enough.
No, they really don't. The thread model breaks down when you have parallel queues, and when you have retargeted queues. It's just not an accurate model of how GCD works, and I would argue that it has already misled you, as evidenced by your misunderstanding of dispatch_sync.

Replace where I said thread with Queue. Queue A and Queue B have to stop while Queue C finishes.
There is no queue C, just as there was no thread C.

How good do you need your random numbers to be?
Uniformly distributed and subject to two constraints.
〈Lᵢ(t)〉 = 0
〈Lᵢ(t)Lᵣ(t')〉 = δᵢᵣδ(t - t')
Fucked if I know what that means, I'm afraid. The only statistical function L I've ever used is likelihood, but that makes no sense here.
 

nathematics

Ars Scholae Palatinae
984
DrPizza":2lf71hlj said:
Mark Cianciosa":2lf71hlj said:
DrPizza":2lf71hlj said:
I would strongly recommend you think of them as nothing of the sort. They're not; they don't act like threads, they don't have any particular correspondence with threads, they're a completely different beast.
They act close enough.
No, they really don't. The thread model breaks down when you have parallel queues, and when you have retargeted queues. It's just not an accurate model of how GCD works, and I would argue that it has already misled you, as evidenced by your misunderstanding of dispatch_sync.

Replace where I said thread with Queue. Queue A and Queue B have to stop while Queue C finishes.
There is no queue C, just as there was no thread C.

How good do you need your random numbers to be?
Uniformly distributed and subject to two constraints.
〈Lᵢ(t)〉 = 0
〈Lᵢ(t)Lᵣ(t')〉 = δᵢᵣδ(t - t')
Fucked if I know what that means, I'm afraid. The only statistical function L I've ever used is likelihood, but that makes no sense here.


I'm not sure but I would guess this:

Lᵢ(t) is a random sequence of numbers. 〈Lᵢ(t)〉 is the average* of Lᵢ(t), and 〈Lᵢ(t)Lᵣ(t')〉 is the average crosscorrelation of the sequence Li(t) with a separate, time sequence we don't know about Lᵣ(t'). That is to say the second equation specifies the average value of the dot product between the sequence Lᵢ(t) and another sequence Lᵣ(t'). If I had to interpret that, it would be a time shifted Dirac delta function times "δᵢᵣ" which makes little sense to me, as  appears to be a 2x2 matrix, and δᵢᵣ is unknown to me.

Edit:

*I think the brackets indicate time averages. The is the integral of Li(i) dt divided by the difference between the start and end time values of integration.
 

Mark Cianciosa

Wise, Aged Ars Veteran
161
DrPizza":2c5z6715 said:
No, they really don't. The thread model breaks down when you have parallel queues, and when you have retargeted queues. It's just not an accurate model of how GCD works, and I would argue that it has already misled you, as evidenced by your misunderstanding of dispatch_sync.
There is no queue C, just as there was no thread C.
The end result is exactly the same. When you have a global queue you effectively have two or more concurrent queues on a two processor system. The serial queue is effectively a third queue. The end result is the same. If there are two blocks running and both submit a block to the same serial queue then both blocks can't do anything until the block submitted to the serial queue is don't. That is analogous to two threads having to wait for a third thread to finish before the third thread can continue. Whatever GCD does under the hood is irrelevant. The end result is exactly the same.
 

Mark Cianciosa

Wise, Aged Ars Veteran
161
nathematics":133w2jy3 said:
I'm not sure but I would guess this:

Lᵢ(t) is a random sequence of numbers. 〈Lᵢ(t)〉 is the average* of Lᵢ(t), and 〈Lᵢ(t)Lᵣ(t')〉 is the average crosscorrelation of the sequence Li(t) with a separate, time sequence we don't know about Lᵣ(t'). That is to say the second equation specifies the average value of the dot product between the sequence Lᵢ(t) and another sequence Lᵣ(t'). If I had to interpret that, it would be a time shifted Dirac delta function times "δᵢᵣ" which makes little sense to me, as  appears to be a 2x2 matrix, and δᵢᵣ is unknown to me.

Edit:

*I think the brackets indicate time averages. The is the integral of Li(i) dt divided by the difference between the start and end time values of integration.
Correct

δᵢᵣ is a Kronecker Delta: δᵢᵣ = 1, if i = r and 0, if i ≠ r

It means any randomness applied to particle i at a time t must not be correlated with any other randomness applied to any other particle at any time or the same particle at any other time. It's just a mathematical way of saying white noise.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
Can't you just precalculate a whole bunch of randomness with the desired characteristics.

The memory use wouldn't be great but if you could keep each queue reading from it's own sequential pool it should be way faster than anything trying to cleanly generate it on the fly (unless you have some kit generating your random noise in which case ignore what I'm saying
 
Mark Cianciosa":1dmqe561 said:
The end result is exactly the same. When you have a global queue you effectively have two or more concurrent queues on a two processor system. The serial queue is effectively a third queue. The end result is the same. If there are two blocks running and both submit a block to the same serial queue then both blocks can't do anything until the block submitted to the serial queue is don't. That is analogous to two threads having to wait for a third thread to finish before the third thread can continue. Whatever GCD does under the hood is irrelevant. The end result is exactly the same.
But it isn't irrelevant, because you're claiming that the queues have to wait in the uncontended case. They would if the queues were all threads. But the queues aren't all threads, and in the uncontended case there is no waiting.
 

Mark Cianciosa

Wise, Aged Ars Veteran
161
DrPizza":f71x6474 said:
But it isn't irrelevant, because you're claiming that the queues have to wait in the uncontended case. They would if the queues were all threads. But the queues aren't all threads, and in the uncontended case there is no waiting.

Of course it's waiting. It has to wait while libdispatch preforms all the checks needed to see if it can safely run the block you just queued, run the block, then clean up after it self.
 
Mark Cianciosa":1iiossss said:
DrPizza":1iiossss said:
But it isn't irrelevant, because you're claiming that the queues have to wait in the uncontended case. They would if the queues were all threads. But the queues aren't all threads, and in the uncontended case there is no waiting.

Of course it's waiting. It has to wait while libdispatch preforms all the checks needed to see if it can safely run the block you just queued, run the block, then clean up after it self.
That's like saying the semaphore has to "wait" because it has to verify that the semaphore isn't already owned. Running code isn't waiting; the thread being unrunnable due to a kernel-mode wait is waiting.
 

Mark Cianciosa

Wise, Aged Ars Veteran
161
DrPizza":252qsrg0 said:
That's like saying the semaphore has to "wait" because it has to verify that the semaphore isn't already owned. Running code isn't waiting; the thread being unrunnable due to a kernel-mode wait is waiting.
A thread waiting being unrunnable due to a kernel-mode wait waiting is just code running too. It's just code come where else.

You can think of dispatch queues as threads and it makes a pretty damn good model.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
What's the equivalent in threading terms of a block on a queue trying to synchronously wait on A block added to the same queue?
Serial queues are nothing like locks in threading terms since it guarantees ordering.
Taking locks inside a block or doing explicit threading operations like yielding are also going to behave very differently.

It's a thread pool, that's the proper way to think about it.
 
Mark Cianciosa":a8cqggap said:
DrPizza":a8cqggap said:
That's like saying the semaphore has to "wait" because it has to verify that the semaphore isn't already owned. Running code isn't waiting; the thread being unrunnable due to a kernel-mode wait is waiting.
A thread waiting being unrunnable due to a kernel-mode wait waiting is just code running too.
Er, no, it isn't. It's not running. That's, like, the entire point.

You can think of dispatch queues as threads and it makes a pretty damn good model.
Except it isn't a good model. There are dispatch queue features it can't handle and it has already led to you misunderstanding how libdispatch works. How you can proclaim it to be a "good model" in spite of that is beyond me. It is plainly deficient as a model.

What source are you using for random numbers?
 

Mark Cianciosa

Wise, Aged Ars Veteran
161
DrPizza":1lq4nwrl said:
Except it isn't a good model. There are dispatch queue features it can't handle and it has already led to you misunderstanding how libdispatch works. How you can proclaim it to be a "good model" in spite of that is beyond me. It is plainly deficient as a model.
You can model orbital motion like a tethered mass. Does that mean there is a rope tying a satellite to the earth? No! But that's irrelevant the essential physics is preserved.

Modeling dispatch queues like threads makes a damn good model. You can predict what will be fast, what will be slow, what will cause crashes, etc. What is under the hood doesn't matter. It gives the same results. It's a damn good model because I used it to predict what would be faster and it turned out to be correct.
What source are you using for random numbers?
Mersenne twister
 

Mark Cianciosa

Wise, Aged Ars Veteran
161
ShuggyCoUk":1wuietcg said:
What's the equivalent in threading terms of a block on a queue trying to synchronously wait on A block added to the same queue?
Having thread A wait on thread A. And that's why it becomes immediately clear why you don't do that and why thinking of queues as threads still makes a damn good model.
 

Mark Cianciosa

Wise, Aged Ars Veteran
161
Let's use this thread model to make a prediction. The dispatching something to a global queue is same result as running something on a different thread. I wonder what will happen if I have a program that does this.
Code:
#include <stdio.h>
#include <dispatch/dispatch.h>

int main (int argc, const char * argv[]) {
    dispatch_sync(dispatch_get_global_queue(0, 0), ^{
        dispatch_sync(dispatch_get_global_queue(0, 0), ^{
            printf("Not dead locked.\n");
        });
    });
    printf("All good.\n");
    return 0;
}
Hmmm? That looks like thread A waiting on thread B. Lets see what happens when I run it.
Code:
Loading program into debugger…
Program loaded.
run
Not dead locked.
All good.
[Switching to process 257]
Running…

Debugger stopped.
Program exited with status value:0.
Look at that just what the model predicted.
 
Mark Cianciosa":dyopni4g said:
Modeling dispatch queues like threads makes a damn good model. You can predict what will be fast, what will be slow, what will cause crashes, etc. What is under the hood doesn't matter. It gives the same results. It's a damn good model because I used it to predict what would be faster and it turned out to be correct.
Not in any meaningful way. 3% is experimental frigging error, not "faster".

Mersenne twister
Hm, that's too bad. If you were using something simple with next to no state (e.g. only a 32- or 64-bit integer) then it would be pretty easy to make it multithreaded and lock-free, and skip that whole mess.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
And that's why it becomes immediately clear why you don't do that and why thinking of queues as threads still makes a damn good model.

Fair point. Here's a better one:
you have 3lock objects, of which you take either A and B or A and C, and a thread based model with a locking protocol to ensure no deadlock (lets say A,B,C).
What's the translation of that to GCD based queues?

In the threading world locks are independent and their ownership transitions between threads. In GCD serial dispatch queues (attempt) to replace locks. But ownership does not transfer. There is no simple translation (the only simple case occurs when there is only one lock so you don't care about the discrepancy).

There are some other things in a more simple vein that have no analogue like thread local storage (for a serial queue you could replicate this without much effort, for a non serial one you can't)
 
Status
Not open for further replies.