This commit is contained in:
2026-05-14 09:27:48 +08:00
parent 1100043d73
commit f8ae30583d
17 changed files with 1007 additions and 0 deletions

7
exp1/.vscode/launch.json vendored Normal file
View File

@@ -0,0 +1,7 @@
{
// 使用 IntelliSense 了解相关属性。
// 悬停以查看现有属性的描述。
// 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": []
}

28
exp1/.vscode/tasks.json vendored Normal file
View File

@@ -0,0 +1,28 @@
{
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: gcc 生成活动文件",
"command": "/usr/bin/gcc",
"args": [
"-fdiagnostics-color=always",
"-g",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "调试器生成的任务。"
}
],
"version": "2.0.0"
}

BIN
exp1/badcount Executable file

Binary file not shown.

62
exp1/badcount.c Normal file
View File

@@ -0,0 +1,62 @@
#include <pthread.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int cnt = 0;
sem_t mutex;
void *increase(void *vargp)
{
unsigned int niters = (unsigned int)vargp;
for (unsigned int i = 0; i < niters; i++)
{
sem_wait(&mutex);
cnt++;
sem_post(&mutex);
}
return NULL;
}
void *decrease(void *vargp)
{
unsigned int niters = (unsigned int)vargp;
for (unsigned int i = 0; i < niters; i++)
{
sem_wait(&mutex);
cnt--;
sem_post(&mutex);
}
return NULL;
}
int main(int argc, char **argv)
{
unsigned int niters;
pthread_t t1,t2;
if (argc != 2)
{
printf("Usage: %s <niters>\n", argv[0]);
exit(2);
}
niters = atoll(argv[1]);
sem_init(&mutex, 0, 1);
pthread_create(&t1,NULL,increase,(void*)niters);
pthread_create(&t2,NULL,decrease,(void*)niters);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
if (cnt != 0)
{
printf("Error! cnt=%d\n", cnt);
}
else
{
printf("Correct! cnt=%d\n", cnt);
}
sem_destroy(&mutex);
exit(0);
}

BIN
exp1/task61 Executable file

Binary file not shown.

53
exp1/task61.c Normal file
View File

@@ -0,0 +1,53 @@
#include <pthread.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void *wokerT1(void *vargp)
{
for(int i=0; i<5; i++)
{
printf("My name is Lvjinzhong\n");
int sleep_time = rand() % 5 + 1;
sleep(sleep_time);
}
return NULL;
}
void *wokerT2(void *vargp)
{
for(int i=0; i<5; i++)
{
printf("My student number is 2024414290124\n");
int sleep_time = rand() % 5 + 1;
sleep(sleep_time);
}
return NULL;
}
void *wokerT3(void *vargp)
{
for(int i=0; i<5; i++)
{
time_t t = time(NULL);
printf("Current time %s\n",ctime(&t));
int sleep_time = rand() % 5 + 1;
sleep(sleep_time);
}
return NULL;
}
int main()
{
pthread_t t1,t2,t3;
pthread_create(&t1, NULL, wokerT1, NULL);
pthread_create(&t2, NULL, wokerT2, NULL);
pthread_create(&t3, NULL, wokerT3, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
pthread_join(t3, NULL);
return 0;
}