《CSAPP》(第3版)答案(第十二章)(一)
P16
#include <stdio.h>
#include "csapp.h"
void *thread(void *vargp);
#define DEFAULT 4
int main(int argc, char* argv[]) {
int N;
if (argc > 2)
unix_error("too many param");
else if (argc == 2)
N = atoi(argv[1]);
else
N = DEFAULT;
int i;
pthread_t tid;
for (i = 0; i < N; i++) {
Pthread_create(&tid, NULL, thread, NULL);
}
Pthread_exit(NULL);
}
void *thread(void *vargp) {
printf("Hello, world\n");
return NULL;
}
P17
#include "csapp.h"
void *thread(void *vargp);
int main()
{
pthread_t tid;
Pthread_create(&tid, NULL, thread, NULL);
Pthread_exit(NULL);
}
void *thread(void *vargp)
{
Sleep(1);
printf("Hello, world!\n");
return NULL;
}
P18
P19
#include <stdio.h>
#include "csapp.h"
#define WRITE_LIMIT 100000
#define PEOPLE 4
static int readtimes;
static int writetimes;
static int readcnt;
static int reader_first;
sem_t mutex, w;
void *reader(void *vargp) {
while (1) {
P(&mutex);
readcnt++;
if (readcnt == 1)
P(&w);
V(&mutex);
readtimes++;
reader_first = 0;
P(&mutex);
readcnt--;
if (readcnt == 0)
V(&w);
V(&mutex);
}
}
void *writer(void *vargp) {
while (1) {
if (reader_first == 1)
continue;
P(&w);
writetimes++;
if (writetimes == WRITE_LIMIT) {
printf("read/write: %d/%d\n", readtimes, writetimes);
exit(0);
}
if (readcnt == 1)
reader_first = 1;
V(&w);
}
}
void init(void) {
readcnt = 0;
readtimes =