Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <pthread.h>
- #include <semaphore.h>
- #include <unistd.h>
- typedef struct {
- int money;
- } account_t;
- account_t acc[3];
- sem_t sem[3];
- void *mainThread(void* arg) {
- int index=*((int*)arg);
- srand((unsigned int)pthread_self());
- int r,rValue;
- while(1) {
- r=rand()%9;
- sleep(r);
- sem_wait(&sem[index]);
- printf("Saldo%d : %d\n",index,acc[index].money);
- sem_post(&sem[index]);
- r=rand()%5;
- rValue=1000+rand()%5001;
- sem_wait(&sem[index]);
- printf("Saldo%d : %d-%d=%d\n",index,acc[index].money,rValue,acc[index].money-rValue);
- acc[index].money-=rValue;
- sem_post(&sem[index]);
- sem_wait(&sem[3-index]);
- printf("Saldo%d : %d+%d=%d\n",3-index,acc[3-index].money,rValue,acc[3-index].money+rValue);
- acc[3-index].money+=rValue;
- sem_post(&sem[3-index]);
- sleep(r);
- }
- pthread_exit(NULL);
- }
- int main(int argc, char **argv) {
- sem_init(&sem[1],0,1);
- sem_init(&sem[2],0,1);
- acc[1].money=acc[2].money=100000;
- pthread_t usr1,usr2;
- int usrIndex1=1,usrIndex2=2;
- pthread_create(&usr1,NULL,mainThread,&usrIndex1);
- pthread_create(&usr2,NULL,mainThread,&usrIndex2);
- while(1) {
- //
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement