monotone

monotone Mtn Source Tree

Root/unix/threads.cc

1// Copyright (C) 2008 Markus Wanner <markus@bluegap.ch>
2//
3// This program is made available under the GNU GPL version 2.0 or
4// greater. See the accompanying file COPYING for details.
5//
6// This program is distributed WITHOUT ANY WARRANTY; without even the
7// implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
8// PURPOSE.
9
10
11// This file provides very basic threading support, just enough to allow
12// multiple worker threads to process small, enclosed jobs concurrently.
13// These jobs need to be separated very well. They get an input and
14// should provide some output, but may not interfere with the rest of
15// monotone in any other way, because we don't want to buy into complex
16// locking problems.
17//
18// When writing jobs for a threaded task, please be aware, that these
19// tasks MUST NOT throw exceptions. Additionally, you have to take care
20// and make sure all objects used by that thread are valid until the job
21// is done. And of course you need to avoid concurrent access to objects.
22
23#include "base.hh"
24#include <pthread.h>
25
26#include "sanity.hh"
27#include "threads.hh"
28
29struct
30thread_context
31{
32 threaded_task * task;
33};
34
35void *threaded_call(void *c)
36{
37 thread_context * ctx = (thread_context*) c;
38 ctx->task->operator()();
39 pthread_exit(NULL);
40}
41
42void
43create_thread_for(threaded_task * task)
44{
45 int rc;
46 void *status;
47 pthread_t thread;
48
49 thread_context * ctx = new thread_context();
50 ctx->task = task;
51
52 rc = pthread_create(&thread, NULL, threaded_call, (void*) ctx);
53 I(!rc);
54
55 rc = pthread_join(thread, &status);
56 I(!rc);
57
58 delete ctx;
59 delete task;
60}
61
62worker_pool::worker_pool()
63 : max_threads(4),
64 num_threads(0)
65{ }
66
67void worker_pool::add_job(threaded_task* t)
68{
69 tstack.push(t);
70}
71
72void worker_pool::wait(void)
73{
74 while (!tstack.empty())
75 {
76 threaded_task *task = tstack.top();
77 tstack.pop();
78 create_thread_for(task);
79 }
80}
81
82// Local Variables:
83// mode: C++
84// fill-column: 76
85// c-file-style: "gnu"
86// indent-tabs-mode: nil
87// End:
88// vim: et:sw=2:sts=2:ts=2:cino=>2s,{s,\:s,+s,t0,g0,^-2,e-2,n-2,p2s,(0,=s:

Archive Download this file

Branches

Tags

Quick Links:     www.monotone.ca    -     Downloads    -     Documentation    -     Wiki    -     Code Forge    -     Build Status