Skip to content
This repository has been archived by the owner on Jun 28, 2019. It is now read-only.

Commit

Permalink
sample/ch12/goodcnt.c: 使用信号量来实现互斥
Browse files Browse the repository at this point in the history
  • Loading branch information
mofaph committed Dec 17, 2013
1 parent 0bade38 commit dbf70f0
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
8 changes: 8 additions & 0 deletions sample/ch12/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,13 @@ OBJS += echoservert.o
OBJS += echo.o
OBJS += sharing.o
OBJS += badcnt.o
OBJS += goodcnt.o

PROGRAMS += hello
PROGRAMS += echoservert
PROGRAMS += sharing
PROGRAMS += badcnt
PROGRAMS += goodcnt

PHONY += all
PHONY += clean
Expand Down Expand Up @@ -60,5 +62,11 @@ badcnt: badcnt.o csapp.o
badcnt.o: badcnt.c $(csapp_h)
$(CC) $(CFLAGS) $(INCLUDES) -c $< -o $@

goodcnt: goodcnt.o csapp.o
$(CC) $(CFLAGS) $^ $(LIBS) -o $@

goodcnt.o: goodcnt.c $(csapp_h)
$(CC) $(CFLAGS) $(INCLUDES) -c $< -o $@

clean:
rm -f $(OBJS) $(PROGRAMS)
58 changes: 58 additions & 0 deletions sample/ch12/goodcnt.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/*
* p669
*
* 使用信号量来实现互斥
*
* 在类 UNIX 系统中编译和运行:
*
* unix> make goodcnt
* unix> ./goodcnt
*/

#include "csapp.h"

void *thread(void *vargp); /* Thread routine prototype */

/* Global shared variable */
volatile int cnt = 0; /* Counter */
sem_t mutex; /* Semaphore that protects counter */

int main(int argc, char **argv)
{
int niters;
pthread_t tid1, tid2;

/* Check input argument */
if (argc != 2) {
printf("usage: %s <niters>\n", argv[0]);
exit(0);
}
niters = atoi(argv[1]);

Sem_init(&mutex, 0, 1); /* mutex = 1 */

/* Created threads and wait for them to finish */
Pthread_create(&tid1, NULL, thread, &niters);
Pthread_create(&tid2, NULL, thread, &niters);
Pthread_join(tid1, NULL);
Pthread_join(tid2, NULL);

/* Check result */
if (cnt != (2 * niters))
printf("BOOM! cnt=%d\n", cnt);
else
printf("OK cnt=%d\n", cnt);
exit(0);
}

/* Thread routine */
void *thread(void *vargp)
{
int i, niters = *((int *)vargp);
for (i = 0; i < niters; i++) {
P(&mutex);
cnt++;
V(&mutex);
}
return NULL;
}

0 comments on commit dbf70f0

Please sign in to comment.