lab2 pthread done

This commit is contained in:
yly 2026-01-19 22:25:53 +08:00
parent 2d1c510b49
commit 34d9ab0e55
9 changed files with 1015808 additions and 36 deletions

1
.gitignore vendored
View File

@ -8,3 +8,4 @@ compile_commands.json
*.swp
# Temporary files
*~
.cache/

1005618
lab2/pthread/InFile1.txt Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,16 +0,0 @@
CC = gcc
CFLAGS = -Wall -Wextra -O2
LDLIBS = -lpthread
SRCS := $(wildcard *.c)
BINS := $(SRCS:.c=)
.PHONY: all clean
all: $(BINS)
%: %.c
$(CC) $(CFLAGS) -o $@ $< $(LDLIBS)
clean:
-rm -f $(BINS) *.o

View File

@ -2,69 +2,135 @@
#include <stdlib.h>
#include <pthread.h>
#include <stdbool.h>
#include <string.h>
#include <sys/time.h>
#define NUM_THREADS 4
FILE *fd;
int TotalEvenWords = 0, TotalOddWords = 0, TotalWords = 0;
pthread_mutex_t mutex;
struct Result {
int words;
int even;
int odd;
};
int GetNextLine(FILE *f, char *Line)
{
if (fgets(Line, 132, f)==NULL) if (feof(f))return EOF; else return 1;
}
int GetWordAndLetterCount(char *Line)
struct Result GetWordAndLetterCount(char *Line)
{
int Word_Count = 0, Letter_Count = 0;
int Word_Count = 0, Letter_Count = 0, Even_Count = 0, Odd_Count = 0;
for (int i=0;i<132;i++)
{
if ((Line[i]!=' ')&&(Line[i]!=0)&&(Line[i]!='\n')) Letter_Count++;
else {
if (Letter_Count % 2) {
TotalOddWords++;
Odd_Count++;
Word_Count++;
Letter_Count = 0;
}
else {
TotalEvenWords++;
Even_Count++;
Word_Count++;
Letter_Count = 0;
}
if (Line[i]==0) break;
}
}
return (Word_Count);
// encode two return values
struct Result r = {Word_Count, Even_Count, Odd_Count};
return r;
}
int CountWords()
struct ThreadData {
char **lines;
int start_line;
int end_line;
};
void *count_words_thread(void *arg)
{
bool bDone = false;
char inLine[132];
while (!bDone)
{
bDone = (GetNextLine(fd, inLine) == EOF);
if (!bDone){
TotalWords += GetWordAndLetterCount(inLine) ;
}
}
return 0;
struct ThreadData *data = (struct ThreadData *)arg;
for (int i = data->start_line; i < data->end_line; i++) {
struct Result r = GetWordAndLetterCount(data->lines[i]);
pthread_mutex_lock(&mutex);
TotalWords += r.words;
TotalEvenWords += r.even;
TotalOddWords += r.odd;
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main()
{
fd = fopen("./InFile1.txt", "r"); // Open file for read
if (fd == NULL) {
perror("Failed to open file");
return 1;
}
// Read all lines
char **lines = NULL;
int total_lines = 0;
char buffer[132];
while (fgets(buffer, sizeof(buffer), fd) != NULL) {
lines = realloc(lines, (total_lines + 1) * sizeof(char *));
lines[total_lines] = strdup(buffer);
total_lines++;
}
fclose(fd);
if (total_lines == 0) {
printf("No lines in file\n");
return 0;
}
struct timeval TimeStampStart, TimeStampStop;
double ExeTime;
gettimeofday(&TimeStampStart, NULL);
CountWords();
// Initialize mutex
pthread_mutex_init(&mutex, NULL);
// Create threads
pthread_t threads[NUM_THREADS];
struct ThreadData thread_data[NUM_THREADS];
int lines_per_thread = total_lines / NUM_THREADS;
int remainder = total_lines % NUM_THREADS;
int start = 0;
for (int i = 0; i < NUM_THREADS; i++) {
int end = start + lines_per_thread + (i < remainder ? 1 : 0);
thread_data[i].lines = lines;
thread_data[i].start_line = start;
thread_data[i].end_line = end;
pthread_create(&threads[i], NULL, count_words_thread, &thread_data[i]);
start = end;
}
// Wait for threads
for (int i = 0; i < NUM_THREADS; i++) {
pthread_join(threads[i], NULL);
}
// Destroy mutex
pthread_mutex_destroy(&mutex);
gettimeofday(&TimeStampStop, NULL);
ExeTime = (double)(TimeStampStop.tv_sec - TimeStampStart.tv_sec) +
(double)(TimeStampStop.tv_usec - TimeStampStart.tv_usec) * 1e-6;
fclose(fd);
// Free memory
for (int i = 0; i < total_lines; i++) {
free(lines[i]);
}
free(lines);
printf("Total Words = %8d\n", TotalWords);
printf("Total Even Words = %7d\nTotal Odd Words = %7d\n", TotalEvenWords, TotalOddWords);

View File

@ -0,0 +1,143 @@
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <stdbool.h>
#include <string.h>
#include <sys/time.h>
#define NUM_THREADS 4
FILE *fd;
int TotalEvenWords = 0, TotalOddWords = 0, TotalWords = 0;
pthread_mutex_t mutex;
struct Result {
int words;
int even;
int odd;
};
int GetNextLine(FILE *f, char *Line)
{
if (fgets(Line, 132, f)==NULL) if (feof(f))return EOF; else return 1;
}
struct Result GetWordAndLetterCount(char *Line)
{
int Word_Count = 0, Letter_Count = 0, Even_Count = 0, Odd_Count = 0;
for (int i=0;i<132;i++)
{
if ((Line[i]!=' ')&&(Line[i]!=0)&&(Line[i]!='\n')) Letter_Count++;
else {
if (Letter_Count % 2) {
Odd_Count++;
Word_Count++;
Letter_Count = 0;
}
else {
Even_Count++;
Word_Count++;
Letter_Count = 0;
}
if (Line[i]==0) break;
}
}
struct Result r = {Word_Count, Even_Count, Odd_Count};
return r;
}
struct ThreadData {
char **lines;
int start_line;
int end_line;
};
void *count_words_thread(void *arg)
{
struct ThreadData *data = (struct ThreadData *)arg;
int local_words = 0, local_even = 0, local_odd = 0;
for (int i = data->start_line; i < data->end_line; i++) {
struct Result r = GetWordAndLetterCount(data->lines[i]);
local_words += r.words;
local_even += r.even;
local_odd += r.odd;
}
pthread_mutex_lock(&mutex);
TotalWords += local_words;
TotalEvenWords += local_even;
TotalOddWords += local_odd;
pthread_mutex_unlock(&mutex);
return NULL;
}
int main()
{
fd = fopen("./InFile1.txt", "r"); // Open file for read
if (fd == NULL) {
perror("Failed to open file");
return 1;
}
// Read all lines
char **lines = NULL;
int total_lines = 0;
char buffer[132];
while (fgets(buffer, sizeof(buffer), fd) != NULL) {
lines = realloc(lines, (total_lines + 1) * sizeof(char *));
lines[total_lines] = strdup(buffer);
total_lines++;
}
fclose(fd);
if (total_lines == 0) {
printf("No lines in file\n");
return 0;
}
struct timeval TimeStampStart, TimeStampStop;
double ExeTime;
gettimeofday(&TimeStampStart, NULL);
// Initialize mutex
pthread_mutex_init(&mutex, NULL);
// Create threads
pthread_t threads[NUM_THREADS];
struct ThreadData thread_data[NUM_THREADS];
int lines_per_thread = total_lines / NUM_THREADS;
int remainder = total_lines % NUM_THREADS;
int start = 0;
for (int i = 0; i < NUM_THREADS; i++) {
int end = start + lines_per_thread + (i < remainder ? 1 : 0);
thread_data[i].lines = lines;
thread_data[i].start_line = start;
thread_data[i].end_line = end;
pthread_create(&threads[i], NULL, count_words_thread, &thread_data[i]);
start = end;
}
// Wait for threads
for (int i = 0; i < NUM_THREADS; i++) {
pthread_join(threads[i], NULL);
}
// Destroy mutex
pthread_mutex_destroy(&mutex);
gettimeofday(&TimeStampStop, NULL);
ExeTime = (double)(TimeStampStop.tv_sec - TimeStampStart.tv_sec) +
(double)(TimeStampStop.tv_usec - TimeStampStart.tv_usec) * 1e-6;
// Free memory
for (int i = 0; i < total_lines; i++) {
free(lines[i]);
}
free(lines);
printf("Total Words = %8d\n", TotalWords);
printf("Total Even Words = %7d\nTotal Odd Words = %7d\n", TotalEvenWords, TotalOddWords);
printf("The time to count word was %f seconds\n", (ExeTime));
return 0;
}

71
lab2/pthread/pi_par.c Normal file
View File

@ -0,0 +1,71 @@
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/time.h>
#define NUM_THREADS 4
long long num_steps = 1000000000;
double step;
double global_sum = 0.0;
pthread_mutex_t mutex;
void *compute_pi(void *arg) {
int thread_id = *(int *)arg;
double local_sum = 0.0;
long long start = thread_id * (num_steps / NUM_THREADS);
long long end = (thread_id + 1) * (num_steps / NUM_THREADS);
if (thread_id == NUM_THREADS - 1) end = num_steps; // Handle remainder
for (long long i = start; i < end; i++) {
double x = (i + 0.5) * step;
local_sum += 4.0 / (1.0 + x * x);
}
pthread_mutex_lock(&mutex);
global_sum += local_sum;
pthread_mutex_unlock(&mutex);
return NULL;
}
int main(int argc, char* argv[])
{
struct timeval TimeStampStart, TimeStampStop;
double ExeTime;
double pi;
int thread_ids[NUM_THREADS];
pthread_t threads[NUM_THREADS];
step = 1.0 / (double)num_steps;
// Initialize mutex
pthread_mutex_init(&mutex, NULL);
gettimeofday(&TimeStampStart, NULL);
// Create threads
for (int i = 0; i < NUM_THREADS; i++) {
thread_ids[i] = i;
pthread_create(&threads[i], NULL, compute_pi, &thread_ids[i]);
}
// Wait for threads
for (int i = 0; i < NUM_THREADS; i++) {
pthread_join(threads[i], NULL);
}
pi = global_sum * step;
gettimeofday(&TimeStampStop, NULL);
ExeTime = (double)(TimeStampStop.tv_sec - TimeStampStart.tv_sec) +
(double)(TimeStampStop.tv_usec - TimeStampStart.tv_usec) * 1e-6;
// Destroy mutex
pthread_mutex_destroy(&mutex);
printf("The value of PI is %15.12f\n", pi);
printf("The time to calculate PI was %f seconds\n", ExeTime);
return 0;
}

9859
lab2/pthread/rfc2616.txt Normal file

File diff suppressed because it is too large Load Diff

30
lab2/pthread/xmake.lua Normal file
View File

@ -0,0 +1,30 @@
set_xmakever("2.8.2")
set_project("pthread-lab")
set_version("1.0.0")
add_rules("mode.debug", "mode.release")
target("count_words_par")
set_kind("binary")
add_files("count_words_par.c")
add_links("pthread")
target("count_words_ser")
set_kind("binary")
add_files("count_words_ser.c")
target("pi_ser")
set_kind("binary")
add_files("pi_ser.c")
add_links("pthread")
target("pi_par")
set_kind("binary")
add_files("pi_par.c")
add_links("pthread")
target("pthread_hello")
set_kind("binary")
add_files("pthread_hello.c")
add_links("pthread")