Lecture Notes for CS 509, Advanced Programming II

3 March 2004 - Thread Iterators


Outline


Client-Server Computing


Creating Threads


Joining Threads


Creating Threads


Non-Loopy Code


Vector-Based Thread Creation


Thread Iterators


Implementing Thread Iterators

class thread_iterator 

  public:

    thread_iterator() 
      : cnt(0), tmain(0), tid(0)

    thread_iterator(int i, void* (*f)(void*)) 
      : cnt(i), tmain(f), tid(0)

    thread_iterator(const thread_iterator & i) 
      : cnt(i.cnt) tmain(i.tmain) tid(i.tid)

  private:

    unsigned cnt
    void * (* tmain)(void *)
    pthread_t tid


Implementing the Methods


Implementing the Methods, Continued


Using Thread Iterators

$ cat ti.cc
int main()

  const unsigned max = 3
  std::vector<pthread_t> tids

  std::copy(thread_iterator(max, client),
	    thread_iterator(),
	    std::back_inserter(tids))
  std::for_each(tids.begin(), tids.end(), join)

$ g++ -o ti -ansi -pedantic ti.cc -lpthread

$ ./ti
thread thread thread thread 2 is alive.
3 is alive.
0 is alive.
1 is alive.

$ CC -o ti ti.cc -lpthread

$ ./ti
thread 0 is alive.
thread 1 is alive.
thread 2 is alive.
thread 3 is alive.

$ 

See the complete code.


Points to Remember


This page last modified on 12 March 2004.