Uncategorized

Thread stack in heap (pthreads)

I had known that a thread has a stack. But never thought where is this stack lie in the memory?

Well, it should be process stack. But you can set the thread stack to a heap area.

How to do that?

#include "pthread.h"
#include "stdio.h"
#include "unistd.h"
pthread_mutex_t mutex1;
void* foo(void *arg)
{
 int arr[1024*8];
 int x = 0;
 while(x++ < (8*1024) )
 { arr[x] = x; }
 pthread_mutex_lock(&mutex1);
 puts("Thread created");
 pthread_mutex_unlock(&mutex1);
}
int main()
{
 int *p;
 void *ret; 
 p = malloc(1024); 
 free(p);
 pthread_attr_t attr;
 pthread_attr_setstack(&attr, p, 2);
 pthread_t thread1;
 pthread_create(&thread1, NULL, foo, NULL);
 pthread_join(thread1, &ret); 
 free(p);
 return 0;
}

But still I am a lot to learn…

Advertisements

Categories: Uncategorized

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.