Archive for the ‘C/C++’ Category

pthreads – Some useful links and solution for maximum thread number

July 21, 2009

Manual Reference Pages (including a list of functions that are not thread-safe)

Tutorial on pthreads

And if you wonder why you cannot create more than X threads on your system (for me this was always 382), this forum provides a solution.

Basically, the problem is that each thread created will occupy space for its stack. On my system, the default thread stack size is 8MB. Therefore, after 382, I simply run out of space.

Solution: Change the stack size to a smaller value, unless you really need 8MB.

pthread_attr_t tattr;
size_t size;
size = PTHREAD_STACK_MIN + WHAT_ELSE_YOU_NEED;
pthread_attr_init(&tattr);
pthread_attr_setstacksize(&tattr, size);

Another interesting page on pthreads is this.

Profiling Code Using clock_gettime

July 6, 2009

Find a good explanation here written by Guy Rutenberg.

Using the GPIO on a tmote to make a LED blink

January 17, 2008

I know this might sound pretty silly, but since I couldn’t find anywhere else how to do it, and I had to spend quite a lot of time figuring it out myself, I decided to post it. So, if you need to interface a brighter LED on a tmote sky (or whatever needs a digital input), connect the ground of the LED to pin 9 of the 10-pin expansion header of the tmote, and the other cable to pin 3 of the 6-pin expansion header (which is GPIO port 2, refer to the tmote datasheet for more info). After that, you need to write a proper “driver” to set pin 2.3 of the msp430 (tmote’s CPU) to 1 or 0. You can use the following macros:

 

#define P23_OUT() P2DIR |= BV(3)
#define P23_IN() P2DIR &= ~BV(3)
#define P23_SEL() P2SEL &= ~BV(3)
#define P23_IS_1  (P2OUT & BV(3))
#define P23_WAIT_FOR_1() do{}while (!P23_IS_1)
#define P23_IS_0  (P2OUT & ~BV(3))
#define P23_WAIT_FOR_0() do{}while (!P23_IS_0)
#define P23_1() P2OUT |= BV(3)
#define P23_0() P2OUT &= ~BV(3)

For example, to make the led blink at intervals of 1 sec (this is contiki code, but apart from the timer it’s standard C):

 

P23_OUT();
P23_SEL();

while(1)
{
	etimer_set(&mytimer, CLOCK_SECOND);
	PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&mytimer));
	
	if(toggle==0)
	{
		printf("Changing 1\n");
		toggle=1;
		P23_1();
		printf("It's one\n");
	}
	else
	{
		printf("Changing 0\n");
		toggle=0;
		P23_0();
		printf("It's zero\n");
	}
} 

How to read from a file in C++

November 28, 2007

This is a basic example how to read from a file in C++ without much error checking or anything. If you want to have a look at the ifstream reference, it’s here.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
  ifstream file;
  string line;
  file.open("./myfile.txt");
  if (!file.is_open()){
     cerr << "Oops. Could not open file." << endl;
     return -1;
  }
  while (!file.eof()) {
     getline(file, line);
     cout << line << endl;
  }
  file.close();
}

Follow

Get every new post delivered to your Inbox.