-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy paththread.cpp
More file actions
51 lines (41 loc) · 1.1 KB
/
thread.cpp
File metadata and controls
51 lines (41 loc) · 1.1 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
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include "thread.h"
static int g_tid = 0;
static int fib(int n){
switch (n) {
case 0: return 1;
case 1: return 1;
default: return (fib(n-2) + fib(n-1));
}
}
void * thread_proc(void* ctx)
{
int tid = g_tid++;
char thread_name[16];
snprintf(thread_name, sizeof(thread_name), "Thread %d", tid); // ✅ replaced sprintf with snprintf
#ifdef __APPLE__
pthread_setname_np(thread_name);
#else
pthread_setname_np(pthread_self(), thread_name);
#endif
// Random delay, 0 - 0.5 sec
timespec ts;
ts.tv_sec = 0;
ts.tv_nsec = 500000000 + ((float)rand() / (float)RAND_MAX) * 500000000;
nanosleep(&ts, NULL);
volatile int i = 0;
while (i <= 30) {
std::cout << "Thread " << tid << ": fib(" << i << ") = " << fib(i) << std::endl;
i++;
nanosleep(&ts, NULL);
}
std::cout << thread_name << " exited!" << std::endl;
return nullptr; // ✅ fixed missing return
}