Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <stdio.h>
- #include <pthread.h>
- static pthread_mutex_t cs_mutex;
- typedef struct {
- int c;
- int *red;
- } st;
- void* print(void *pParam) {
- int c = ((st*)pParam)->c;
- int *red = ((st*)pParam)->red;
- int i;
- for(i = 0; i < 1000; i++) {
- int b = 0;
- while (!b) {
- pthread_mutex_lock(&cs_mutex);
- b = (*red == c);
- pthread_mutex_unlock(&cs_mutex);
- };
- pthread_mutex_lock(&cs_mutex);
- printf("%d", c + 1);
- fflush(stdout);
- *red = (*red + 1) % 3;
- pthread_mutex_unlock(&cs_mutex);
- }
- return 0;
- }
- int main(void) {
- pthread_t hPrint1;
- pthread_t hPrint2;
- pthread_t hPrint3;
- pthread_mutex_init(&cs_mutex, NULL);
- st str[3];
- int red = 0;
- int i;
- for (i = 0; i < 3; i++) {
- str[i].c = i;
- str[i].red = &red;
- }
- pthread_create(&hPrint1, NULL, print, (void*)&str[0]);
- pthread_create(&hPrint2, NULL, print, (void*)&str[1]);
- pthread_create(&hPrint3, NULL, print, (void*)&str[2]);
- getchar();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement