-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_thread.c
More file actions
70 lines (55 loc) · 2.12 KB
/
test_thread.c
File metadata and controls
70 lines (55 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <windows.h>
#include <stdio.h>
// Thread function
DWORD WINAPI ThreadFunction(LPVOID param) {
int thread_num = (int)(uintptr_t)param;
char filename[64];
sprintf(filename, "thread_%d.txt", thread_num);
printf("[Thread %d] Starting...\n", thread_num);
// Create file
HANDLE hFile = CreateFileA(filename, GENERIC_WRITE, 0, NULL,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE) {
printf("[Thread %d] ERROR: CreateFile failed\n", thread_num);
return 1;
}
// Write data
char buffer[256];
sprintf(buffer, "Hello from thread %d!\n", thread_num);
DWORD written = 0;
if (!WriteFile(hFile, buffer, strlen(buffer), &written, NULL)) {
printf("[Thread %d] ERROR: WriteFile failed\n", thread_num);
CloseHandle(hFile);
return 1;
}
printf("[Thread %d] Wrote %lu bytes to %s\n", thread_num, written, filename);
CloseHandle(hFile);
printf("[Thread %d] Complete!\n", thread_num);
return 0;
}
int main() {
printf("Testing multi-threaded file I/O\n\n");
const int NUM_THREADS = 3;
HANDLE threads[NUM_THREADS];
DWORD threadIds[NUM_THREADS];
// Create threads
for (int i = 0; i < NUM_THREADS; i++) {
printf("Creating thread %d...\n", i);
threads[i] = CreateThread(
NULL, // Security attributes
0, // Stack size (0 = default)
ThreadFunction, // Thread function
(LPVOID)(uintptr_t)i, // Thread parameter
0, // Creation flags
&threadIds[i] // Thread ID
);
if (threads[i] == NULL) {
printf("ERROR: CreateThread %d failed\n", i);
return 1;
}
printf("Thread %d created: TID=%lu\n", i, threadIds[i]);
}
printf("\n✅ All threads created successfully!\n");
printf("🏴☠️ Multi-threaded file I/O test complete!\n");
return 0;
}