Anonymous user
Metered concurrency: Difference between revisions
→{{header|C}}: using actual semaphore
(→{{header|C}}: using actual semaphore) |
|||
Line 122:
=={{header|C}}==
{{works with|POSIX}}
<lang c>#include <
#include <stdlib.h>▼
#include <sys/types.h>▼
#include <pthread.h>
▲#include <stdlib.h>
#include <unistd.h>
sem_t sem;
#define getcount() count
void acquire()
{
sem_wait(&sem);
count--;
}
void release()
{
count++;
sem_post(&sem);
}
int getcnt()▼
{
int i
while (i--) {
usleep(rand() % 4000000); /* sleep 2 sec on average */
return rc;▼
usleep(0); /* effectively yield */
}▼
}
{▼
pthread_t th[4];
int i, ids[] = {1, 2, 3, 4};
sem_init(&sem, 0, count);
▲int running = 1;
for (i = 4; i--;) pthread_create(th + i, 0, work, ids + i);
printf("all workers done\n");
return sem_destroy(&sem);
▲void *worker(void *d)
}</lang>▼
▲{
▲ acquire();
▲ printf("%08X acquired semaphore (%d)\n", pthread_self(), getcnt());
▲ release();
▲}
▲ pthread_join(workers[i], NULL);
▲}</lang>
=={{header|C sharp}}==
C# has built in semaphore system where acquire is called via Wait(), release with Release() and count with semaphore.CurrentCount.
|