Friday, June 08, 2012

Processes Vs. Threads revisited

http://objectlayer.blogspot.ca/2006/05/thread-vs-process.html
- All threads in a program must run the same executable.A child process, on the
other hand, may run a different executable by calling an exec function.
- An errant thread can harm other threads in the same process because threads
share the same virtual memory space and other resources. For instance, a wild
memory write through an uninitialized pointer in one thread can corrupt
memory visible to another thread.
An errant process, on the other hand, cannot do so because each process has a
copy of the program’s memory space.
- Copying memory for a new process adds an additional performance overhead
relative to creating a new thread. However, the copy is performed only when
the memory is changed, so the penalty is minimal if the child process only reads
memory.
- Threads should be used for programs that need fine-grained parallelism. For
example, if a problem can be broken into multiple, nearly identical tasks, threads
may be a good choice. Processes should be used for programs that need coarser
parallelism.
- Sharing data among threads is trivial because threads share the same memory.
(However, great care must be taken to avoid race conditions, as described previously.)
Sharing data among processes requires the use of IPC mechanisms, as
described in Chapter 5.This can be more cumbersome but makes multiple
processes less likely to suffer from concurrency bugs.
- Thread has its own Code, Data, Stack and Thread is sharing. Each Process has one or more threads and each thread belongs to one process
- Thread is fast for context switch and cheaper than process.
Conceptually, a thread exists within a process.Threads
Simple process for ls

#include <pthread.h>
int main()
{
  int return_value;
  return_value = system ("ls -l /");
  return return_value;
}



#include <pthread.h>
#include <stdio.h>
/* Prints x’s to stderr.*/
void* print_xs (void* unused)
{
    while (1)
    fputc ('x', stderr);
    return NULL;
}
/* The main program.
*/
int main ()
{
    pthread_t thread_id;
    /* Create a new thread. The new thread will run the print_xs
    function. */
    pthread_create (&thread_id, NULL, &print_xs, NULL);
    /* Print o’s continuously to stderr. */
    while (1)
    fputc ('o', stderr);
    return 0;
}
Compile and link this program using the following code:
$ gcc -o thread-create thread-create.c -lpthread
$ ./thread-create
ooooxxxxxxxxxxxxxxooooo

No comments: