-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththreads.C
More file actions
56 lines (47 loc) · 1.25 KB
/
Copy paththreads.C
File metadata and controls
56 lines (47 loc) · 1.25 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
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <stdint.h>
#include <unistd.h>
#include <atomic>
using namespace std;
#define NUM_THREADS 5
static atomic_int sid;
void *PrintHello(void *threadid) {
long tid;
tid = (long)threadid;
int id=1;
while(id<=5) {
cout << "\nHello World! Thread ID, " << tid <<", SID : " <<tid<<"-"<<sid<<endl;
//sleep(1);
id++;
sid++;
}
pthread_exit(NULL);
}
int main () {
pthread_t threads[NUM_THREADS];
pthread_attr_t attr;
void *status;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
int rc;
int i;
for( i=0; i < NUM_THREADS; i++ ){
cout << "\nmain() : creating thread : "<<i<<endl;
rc = pthread_create(&threads[i], &attr, PrintHello, (void *)(intptr_t)i);
//rc = pthread_create(&threads, &attr, PrintHello, (void *)(intptr_t)i);
if (rc){
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
}
cout<<"\nMain Thread is done..\n\n";
pthread_attr_destroy(&attr);
//pthread_detach (threads);
for( i=0; i < NUM_THREADS; i++ ) {
pthread_join(threads[i], &status);
cout << "Main: completed thread id :" << i <<endl;
}
pthread_exit(NULL);
}