|
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ |
|
2 /* vim:set ts=2 sw=2 sts=2 et cindent: */ |
|
3 /* This Source Code Form is subject to the terms of the Mozilla Public |
|
4 * License, v. 2.0. If a copy of the MPL was not distributed with this |
|
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
|
6 |
|
7 #include <stdio.h> |
|
8 #include <stdlib.h> |
|
9 #include "nsXPCOM.h" |
|
10 #include "nsXPCOMCIDInternal.h" |
|
11 #include "nsIThreadPool.h" |
|
12 #include "nsComponentManagerUtils.h" |
|
13 #include "nsCOMPtr.h" |
|
14 #include "nsIRunnable.h" |
|
15 |
|
16 class Task : public nsIRunnable |
|
17 { |
|
18 public: |
|
19 NS_DECL_THREADSAFE_ISUPPORTS |
|
20 |
|
21 Task(int i) : mIndex(i) {} |
|
22 |
|
23 NS_IMETHOD Run() |
|
24 { |
|
25 printf("###(%d) running from thread: %p\n", mIndex, (void *) PR_GetCurrentThread()); |
|
26 int r = (int) ((float) rand() * 200 / RAND_MAX); |
|
27 PR_Sleep(PR_MillisecondsToInterval(r)); |
|
28 printf("###(%d) exiting from thread: %p\n", mIndex, (void *) PR_GetCurrentThread()); |
|
29 return NS_OK; |
|
30 } |
|
31 |
|
32 private: |
|
33 int mIndex; |
|
34 }; |
|
35 NS_IMPL_ISUPPORTS(Task, nsIRunnable) |
|
36 |
|
37 static nsresult |
|
38 RunTests() |
|
39 { |
|
40 nsCOMPtr<nsIThreadPool> pool = do_CreateInstance(NS_THREADPOOL_CONTRACTID); |
|
41 NS_ENSURE_STATE(pool); |
|
42 |
|
43 for (int i = 0; i < 100; ++i) { |
|
44 nsCOMPtr<nsIRunnable> task = new Task(i); |
|
45 NS_ENSURE_TRUE(task, NS_ERROR_OUT_OF_MEMORY); |
|
46 |
|
47 pool->Dispatch(task, NS_DISPATCH_NORMAL); |
|
48 } |
|
49 |
|
50 pool->Shutdown(); |
|
51 return NS_OK; |
|
52 } |
|
53 |
|
54 int |
|
55 main(int argc, char **argv) |
|
56 { |
|
57 if (NS_FAILED(NS_InitXPCOM2(nullptr, nullptr, nullptr))) |
|
58 return -1; |
|
59 RunTests(); |
|
60 NS_ShutdownXPCOM(nullptr); |
|
61 return 0; |
|
62 } |