《CSAPP》(第3版)答案(第十二章)(一)

《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

  • A
    主线程没有等待另一个线程。
  • B
#include "csapp.h"

void *thread(void *vargp);
int main()
{
   
  pthread_t tid;
  
  Pthread_create(&tid, NULL, thread, NULL);
  // exit(0);
  Pthread_exit(NULL);
}

/* Thread routine */
void *thread(void *vargp)
{
   
  Sleep(1);
  printf("Hello, world!\n");
  return NULL;
}

P18

  • A
    不安全
  • B
    安全
  • C
    不安全

P19

#include <stdio.h>
#include "csapp.h"
#define WRITE_LIMIT 100000
#define PEOPLE 4
static int readtimes;
static int writetimes;
static int readcnt;
// if a reader is waiting when writing, reader first next round
static int reader_first;
sem_t mutex, w;
void *reader(void *vargp) {
   
  while (1) {
   
    P(&mutex);
    readcnt++;
    if (readcnt == 1)
      P(&w);
    V(&mutex);
    /* Critical section */
    readtimes++;
    reader_first = 0;
    /* Critical section */
    P(&mutex);
    readcnt--;
    if (readcnt == 0)
      V(&w);
    V(&mutex);
  }
}
void *writer(void *vargp) {
   
  while (1) {
   
    if (reader_first == 1)
      continue;
    P(&w);
    /* Critical section */
    writetimes++;
    if (writetimes == WRITE_LIMIT) {
   
      printf("read/write: %d/%d\n", readtimes, writetimes);
      exit(0);
    }
    /* Critical section */
    // if a reader is waiting, reader first next round
    if (readcnt == 1)
      reader_first = 1;
    V(&w);
  }
}
void init(void) {
   
  readcnt = 0;
  readtimes = 
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值