Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <pthread.h>
- #include <stdlib.h>
- #include <string.h> // strcpy
- #include <unistd.h> // usleep
- #define MICROS (1)
- #define THREADS (5)
- #define ACCESSES (5)
- char * names[] = {"alpha", "bravo", "charlie", "delta",
- "echo", "foxtrot", "golf", "hotel",
- "india", "juliet", "kilo", "lima",
- "mike", "november", "oscar", "papa",
- "quebec", "romeo", "sierra", "tango",
- "uniform", "victor", "whiskey", "x-ray",
- "yankee", "zulu"};
- // could be a good idea to use XCHG asm operation as atomic
- void mutex_lock();
- void mutex_unlock();
- int mx = 0;
- int counter = 0;
- char pool[128] = {0};
- pthread_t threads[THREADS];
- void fill_pool()
- {
- counter++;
- strcpy(pool, names[random() % 26]);
- }
- void show_pool(int number)
- {
- printf("%04d - %04d - %s\n", counter, number, pool);
- }
- void * thread_fnc(void * index)
- {
- int number = (int)index;
- int i;
- for (i = 0; i < ACCESSES; i++)
- {
- usleep(random() % 10000);
- mutex_lock();
- {
- fill_pool();
- show_pool(number);
- }
- mutex_unlock();
- }
- }
- void mutex_lock()
- {
- while (mx) /* needs atomic */
- {
- usleep(MICROS);
- }
- mx = 1;
- }
- void mutex_unlock()
- {
- mx = 0;
- }
- int main()
- {
- int i;
- printf(" ## - THRD - name\n");
- for (i = 0; i < THREADS; i++)
- pthread_create(&threads[i], NULL, thread_fnc, (void *)i);
- for (i = 0; i < THREADS; i++)
- pthread_join(threads[i], NULL);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment