void *thread_B(void *param) { random_sleep(); sem_wait(sem_BCD); printf("B\n"); sem_post(sem_I); random_sleep(); pthread_exit(NULL); }
void *thread_F(void *param) { random_sleep(); sem_wait(sem_EF); printf("F\n"); sem_post(sem_G); random_sleep(); pthread_exit(NULL); }
void *thread_I(void *param) { random_sleep(); sem_wait(sem_I); sem_wait(sem_I); sem_wait(sem_I); printf("I\n"); random_sleep(); pthread_exit(NULL); }
void spam_log(void *arg) { int i; int tid = (*(int*)arg); int lvl = ((*(int*)arg) % LOG_LVL_MAX) + 1; for (i = 0; i < 10; i++) { random_sleep(); } for (i = 0; i < SPAM_LINES; i++) { if (tid % 2) random_sleep(); LOG(lvl, "[%d/%d] SPAM LOG: %d", lvl, tid, i); } pthread_exit(NULL); }
int main(int argc, char** argv) { pid_t child, returnPid, parentPid; int i, status; parentPid = getpid(); printf("main: parent Pid %d\n", parentPid); for (i = 0; i < 3; i++) { printf("fork child No. %d\n", i+1); child = fork(); if (child == 0) { random_sleep(); // beware of a fork bomb here, Google will know! exit(EXIT_SUCCESS); // exit(EXIT_FAILURE); } else if (child == -1) { perror("Problem while forking"); return 1; } else { printf("main: fork child No. %d with PID %d\n", i+1, child); } } while(1){ returnPid = wait(&status); if (returnPid < 0 ) break; printf("Child process ID as %d with status as %d\n", returnPid, status); } printf("main: ******** ending here *********\n"); return 0; }
int main(int argc, char **argv) { pthread_t tid[N_THREAD]; //tid array of A to I thread int i; //iterator //semaphore malloc sem_BCD = (sem_t *) malloc(sizeof(sem_t)); sem_EF = (sem_t *) malloc(sizeof(sem_t)); sem_G = (sem_t *) malloc(sizeof(sem_t)); sem_I = (sem_t *) malloc(sizeof(sem_t)); //semaphore init sem_init(sem_BCD, 0, 0); sem_init(sem_EF, 0, 0); sem_init(sem_G, 0, 0); sem_init(sem_I, 0, 0); while(1) { printf("\n\nNEW LOOP\n"); //thread creation i = 0; pthread_create(&tid[i++], NULL, thread_A, NULL); pthread_create(&tid[i++], NULL, thread_B, NULL); pthread_create(&tid[i++], NULL, thread_C, NULL); pthread_create(&tid[i++], NULL, thread_DH, NULL); pthread_create(&tid[i++], NULL, thread_E, NULL); pthread_create(&tid[i++], NULL, thread_F, NULL); pthread_create(&tid[i++], NULL, thread_G, NULL); pthread_create(&tid[i++], NULL, thread_I, NULL); random_sleep(); //wait thread destruction for(i=0; i<N_THREAD; i++) { pthread_join(tid[i], NULL); } random_sleep(); } return 0; }