Simple threads with pthread.h in linux

Jun 21, 2011 at 2:10pm
Hey guys :) I have a quick question about pthreads under linux (pthread.h).

Note I am 100% new to threads :P

Is the following code safe? It seems to work perfectly however valgrind complains about uneven new/delete combinations but is unable to locate any definitely lost memory...

Also do the threads die straight away with the program? or do they only die once they finish...?

Thanks in advance :)

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
#include <iostream>
using namespace std;
#include <time.h>
#include <pthread.h>

void* thread1(void* data){
	time_t start = time(0);
	// Print every 1 second for at most, 30 seconds
	while( (int)difftime(time(0), start) < 30 ){
		printf("\n\nI AM THREAD 1!");
		printf("\n\n");
		sleep(1);
	}
	
}

void* thread2(void* data){
	time_t start = time(0);
	// Print every 2 seconds for at most, 30 seconds
	while( (int)difftime(time(0), start) < 30 ){
		printf("\n\nI AM THREAD 2!");
		printf("\n\n");
		sleep(2);
	}
	
}

void* thread10(void* data){
	time_t start = time(0);
	// Print every 10 seconds for at most, 30 seconds
	while( (int)difftime(time(0), start) < 30 ){
		printf("\n\nI AM THREAD 10!");
		printf("\n\n");
		sleep(10);
	}
	
}

int main(){
	
	// create threads
	pthread_t threadOne;
	pthread_t threadTwo;
	pthread_t threadTen;
	
	int result = 0;
	int data = 0;
	
	pthread_create(&threadOne, 0, &thread1, (void*)data);
	pthread_create(&threadTwo, 0, &thread2, (void*)data);
	pthread_create(&threadTen, 0, &thread10, (void*)data);
	
	pthread_detach(threadOne);
	pthread_detach(threadTwo);
	pthread_detach(threadTen);
	
	time_t start = time(0);
	// Print every 5 seconds for at most, 30 seconds
	while( (int)difftime(time(0), start) < 30 ){
		printf("\n\nI AM MAIN!");
		printf("\n\n");
		sleep(5);	
	}
	return 1;
}
Last edited on Jun 21, 2011 at 2:20pm
Jun 21, 2011 at 2:49pm
Hi aatwo,

If you are new to threads and using C++, I highly recommend using the Boost Thread library. Your code will be portable across POSIX and Windows.

It is not wise to detach threads. A thread is a resource and by detaching it from your program you lose control of that resource. It is far better from a resource management perspective to cleanly join all threads created in a program.

It is also bad form to put a "using directive" (line #2) before any other includes. Probably no harm in this case, but definitely a dangerous habit to get into as a C++ programmer.
Topic archived. No new replies allowed.