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 <stdiosemaphore.h>
#include <stdlib.h>
#include <sys/types.h>
#include <pthread.h>
#include <stdlib.h>
#include <sys/typesstdio.h>
#include <unistd.h>
#include <signal.h>
 
sem_t sem;
#define MAX_LOCKS 3
int runningcount = 13;
 
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_cond = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int counter=0;
 
#define getcount() count
void acquire()
{
sem_wait(&sem);
pthread_mutex_lock(&mutex_cond);
count--;
while( counter > MAX_LOCKS)
{
pthread_cond_wait(&cond, &mutex_cond);
}
pthread_mutex_unlock(&mutex_cond);
pthread_mutex_lock(&mutex);
counter++;
pthread_mutex_unlock(&mutex);
}
 
void release()
{
count++;
pthread_mutex_lock(&mutex);
sem_post(&sem);
counter--;
pthread_mutex_unlock(&mutex);
 
pthread_mutex_lock(&mutex_cond);
if ( counter < MAX_LOCKS )
{
pthread_cond_signal(&cond);
}
pthread_mutex_unlock(&mutex_cond);
}
 
void *worker work(void *d id)
int getcnt()
{
int i int= rc10;
while (i--) {
pthread_mutex_lock(&mutex);
acquire();
rc = counter;
printf("#%08Xd acquired semaphoresema at (%d)\n", pthread_self*(int*)id, getcntgetcount());
pthread_mutex_unlock(&mutex);
usleep(rand() % 4000000); /* sleep 2 sec on average */
return rc;
release();
usleep(0); /* effectively yield */
}
return rc0;
}
 
int getcntmain()
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);
for (i = 4; i--;) pthread_join(workersth[i], NULL0);
printf("all workers done\n");
 
return sem_destroy(&sem);
void *worker(void *d)
}</lang>
while(running)
{
acquire();
printf("%08X acquired semaphore (%d)\n", pthread_self(), getcnt());
sleep(2);
release();
sleep(1);
}
 
#define NUM_OF_WORKERS 5
#define MAX_LOCKS 3
 
int main()
{
pthread_t workers[NUM_OF_WORKERS];
int i, err;
for(i=0; i<NUM_OF_WORKERS; i++)
{
err = pthread_create(&workers[i], NULL, worker, NULL);
if ( err )
{
fprintf(stderr, "error creating a thread...");
exit(1);
}
}
sleep(20);
running = 0;
for(i=0;i<NUM_OF_WORKERS; i++)
{
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.
Anonymous user