25
loading...
This website collects cookies to deliver better user experience
fork()
function on Unix (or CreateProcess()
on Windows), where you create an entirely separate process that will do its own things.pthread
library will help you going that route.prodrand()
, that produces random numbers and store them in a bufferconsprime()
, that read from the buffer, discards the non prime numbers and uses the primes for its own purpose.prodrand(buffer buf) {
...
while (1) {
n=rnd();
bufferadd(buf,n);
if (bufferlen(buf) == 10)
consprime(buf);
}
...
}
consprime(buffer buf) {
...
while(1) {
while (bufferlen(buf) > 0) {
... // do stuff with prime number
}
prodrand(buf);
}
...
}
prodrand(buffer buf) {
...
while (1) {
n=rnd();
bufferadd(buf,n);
if (bufferlen(buf) == 10)
yeld();
}
...
}
consprime(buffer buf) {
...
while(1) {
while (bufferlen(buf) > 0) {
...
}
yeld();
}
...
}
... // Somewhere else in the code
while(1) {
prodrand(buf);
consprime(buf);
}
...
yeld()
function. It suspends the function and returns back to the caller. The next time the function will be called, the execution will restart from the instruction below yeld()
. The role of the scheduler is taken by a simple loop that calls the coroutines. If, say, you want to introduce another producer that takes numbers from a file you don't have to change anything except adding the new producer to the loop:... // Somewhere else in the code
while(1) {
prodrand(buf);
prodfile(buf, infile);
consprime(buf);
}
...
nextindex(int *ndx)
{
int n = 0;
while (1) ;
*ndx = n++;
yeld();
}
}
main() {
int x;
...
for (int k =0; k<10; k++) {
nextindex(&x);
printf("index: %d\n",x);
}
}
nextindex()
returns (by yelding), the variable n
will be destroyed as the function stack will be released! We could have n
declared as static
but this can't be a general solution.yeld()
so that the execution can be resumed at the next invocation.getcontext()
and setcontext()
) possibly with Assembler code to cover specific platforms.switch
and while
statements that many define being a product of the Devil himself.// The variables followed by semicolon are preserved between calls
beedef(prodrand, buffer buf;)
{
int n;
while (1) {
if (bufferlen(buf) >= 10)
beeyeld;
bufferadd(buffer, rand());
}
beereturn;
}
beedef(consprime, buffer buf;)
{
int n;
while(1) {
while (bufferlen(buf) > 0) {
n = bufferpop(buf);
if (isprime(n)) process(n);
}
beeyeld;
}
beereturn;
}
int main(int argc, char *argv[])
{
prodrand producer = beenew(prodrand);
consprime consumer = beenew(consprime);
buffer buf;
buf = buffernew();
// producer and consumer share the same buffer.
producer->buf = buf;
consumer->buf = buf;
while ( beefly(producer) || beefly(consumer));
}
25