static void * client(void * arg) // whatever main() const unsigned max = max_open_files() pthread_t tids[max] for (i = 0; i < max; i++) if pthread_create(tids + i, client, i) error("pthread create failed") for (i = 0; i < max; i++) if pthread_join(tids[i], NULL) error("pthread join failed")
for (i = 0; i < max; i++) if pthread_join(tids[i], NULL) error("pthread join failed")
std::for_each()
std::for_each()
ignores the return value, no error checking.
static void join(pthread_t tid) if pthread_join(tid, NULL) error("pthread join failed")
std::for_each(tids, tids + max, join)
for i = 0; i < max; i++ if pthread_create(tids + i, f, i) perror("pthread_create() failed")
tids
.
std::generate()
does that, but what's the function?
static pthread_t ptc() pthread_t tid if pthread_create(&tid, f, 0) perror("pthread_create() failed") return tid
std::generate(tids, tids + max, ptc)
static pthread_t ptc() pthread_t tid if pthread_create(&tid, f, 0) perror("pthread_create() failed") return tid static void join(pthread_t tid) if pthread_join(tid, NULL) error("pthread join failed") main() const unsigned max = max_open_files() pthread_t tids[max] std::generate(tids, tids + max, ptc) std::for_each(tids, tids + max, join)
main() int cnt std::cin >> cnt std::vector<pthread_t> tids(cnt) std::generate( tids.begin(), tids.end(), ptc) std::for_each( tids.begin(), tids.end(), join)
*
, ++
, ==
, and ->
.
*
should return the id of the current thread.
++
each create a new thread.
*++ti
and *it++
do
for thread iterator ti
?
main()
doesn't enter into it, although it could.
main()
.
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
pthread_t operator * () if (tid == 0) and (cnt > 0) ptc(tid, --cnt) return tid
thread_iterator operator ++ () if cnt > 0 ptc(tid, --cnt) return *this thread_iterator operator ++ (int) thread_iterator old(*this) if cnt > 0 ptc(tid, --cnt) return old
++it
is chepar than it++
.
bool operator == (const thread_iterator & ti) return cnt == ti.cnt bool operator != (const thread_iterator & ti) return not this->operator == (ti)
void ptc(pthread_t & tid, int arg) if pthread_create(&tid, tmain, arg) error("pthread create failed")
$ 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.
This page last modified on 12 March 2004.