作业社区
探索学习新天地,共享知识资源!
犹豫就会败北~ 的学生作业:
#include #include #include #include #include #include /** * 基于互斥锁实现生产者与消费者模型 主线程为消费者 n 个子线程作为生产者 */ static int totalNum = 0; // 仓库中产品的数量 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void* product_phread(void* arg) { int count = atoi((char*)arg); // 将argv[2]等字符串,转为数字 int temp; for (int i = 0; i < count; i++) { pthread_mutex_lock(&mutex); temp = totalNum; temp = temp + 1; totalNum = temp; printf("pthread[%ld] product 1 production, totalNum: %d\n", pthread_self(), totalNum); pthread_mutex_unlock(&mutex); } pthread_exit(NULL); } // ./a.out 1 2 4 6 代表有4个线程,每个线程生产的产品数量为 1,2,4,6 int main(int argc, char* argv[]) { if (argc < 2) { printf("[ERROR] arguments error.\n"); exit(EXIT_FAILURE); } // 存储线程id的数组 bool done = false; int costNum = 0; // 总的消费产品数量 int productNum = 0; // 总的生产产品数量 pthread_t* tid = malloc(sizeof(pthread_t) * (argc - 1)); if (tid == NULL) { perror("malloc failed.\n"); exit(EXIT_FAILURE); } for (int i = 0; i < argc - 1; i++) { tid[i] = 0; } // 创建线程 for (int i = 0; i < argc - 1; i++) { int err; productNum += atoi(argv[i + 1]); // 生产产品的总和 err = pthread_create(&tid[i], NULL, product_phread, (void*)argv[i + 1]); if (err != 0) { fprintf(stderr, "[ERROR] pthread_create() failed: %s\n", strerror(err)); exit(EXIT_FAILURE); } printf("thread < %ld> start.\n", tid[i]); } // 消费者消费产品 while (1) { pthread_mutex_lock(&mutex); while (totalNum > 0) { costNum++; printf("customer thread 1 production, producer’s surplus production totalNUM: %d\n", --totalNum); } pthread_mutex_unlock(&mutex); sleep(1); done = costNum >= productNum; if (done) { break; } } // 等待子线程结束 for (int i = 0; i < argc - 1; i++) { pthread_join(tid[i], NULL); } free(tid); return 0; }
慕村6158085 的学生作业:
exec1. #! /bin/bash array=(7 5 6 3 2) i=0 for var in array[@]doecho"{array[@]} do echo "array[@]doecho"{array[i]}:$i" i=expr $i + 1 done exec2. #! /bin/bash array=(I am westos teacher welcome to westos training class) i=0 for var in array[@]dov={array[@]} do v=array[@]dov=var if [ KaTeX parse error: Expected '}', got '#' at position 2: {#̲v} -le 6 ] the…v" fi #i=expr $1 + 1 done
+10