Листинг А.27. Функция main для измерения быстродействия семафоров System V
//bench/incr_svsem1.c
1 #include "unpipc.h"
2 #define MAXNTHREADS 100
3 int nloop;
4 struct {
5 int semid;
6 long counter;
7 } shared;
8 struct sembuf postop, waitop;
9 void *incr(void *);
10 int
11 main(int argc, char **argv)
12 {
13 int i, nthreads;
14 pthread_t tid[MAXNTHREADS];
15 union semun arg;
16 if (argc != 3)
17 err_quit("usage: incr_svseml <#loops> <#threads>");
18 nloop = atoi(argv[1]);
19 nthreads = min(atoi(argv[2]), MAXNTHREADS);
20 /* создание семафора и инициализация его значением 0 */
21 shared.semid = Semget(IPC_PRIVATE, 1, IPC_CREAT | SVSEM_MODE);
22 arg.val =0;
23 Semctl(shared.semid, 0, SETVAL, arg);
24 postop.sem_num = 0; /* инициализация двух структур semop */
25 postop.sem_op = 1;
26 postop.sem_flg = 0;
27 waitop.sem_num = 0;
28 waitop.sem_op = –1;
29 waitop.sem_flg = 0;
30 /* создание всех потоков */
31 Set_concurrency(nthreads);
32 for (i = 0; i < nthreads; i++) {
33 Pthread_create(&tid[i], NULL, incr, NULL);
34 }
35 /* запуск таймера и разблокирование семафора */
36 Start_time();
37 Semop(shared.semid, &postop, 1); /* up by 1 */
38 /* ожидание завершения всех потоков */
39 for (i = 0; i < nthreads; i++) {
40 Pthread_join(tid[i], NULL);
41 }
42 printf("microseconds: %.0f usec\n", Stop_time());
43 if (shared.counter != nloop * nthreads)
44 printf("error: counter = %ld\n", shared, counter);
45 Semctl(shared.semid, 0, IPC_RMID);
46 exit(0);
47 }