Debian Codegraph @

examples/threads/import_win32/import.c

raw symbols SCIP
1 /*
2 import.c -- Execute Lisp code from C-generated threads
3 */
4
5 #include <stdlib.h>
6 #include <stdio.h>
7 #ifndef _MSC_VER
8 # include <unistd.h>
9 # include <pthread.h>
10 #endif
11
12 /*
13 * GOAL: To execute lisp code from threads which have not
14 * been generated by our lisp environment.
15 *
16 * ASSUMES: ECL has been configured with threads (--enable-threads)
17 * and installed somewhere on the path.
18 *
19 * COMPILE: Run "make" from the command line.
20 *
21 *
22 * When this example is compiled and run, it generates a number of
23 * threads, each one executing some interpreted code -- in this case
24 * a bunch of PRINT statements.
25 *
26 * Importing other threads into lisp is possible if these threads have
27 * been intercepted by the garbage collector. The way to do it is to
28 * include the <ecl.h> on the source code that generates the threads,
29 * as we do here. This takes care of replacing calls to phtread_create
30 * or CreateThread (in unix and Windows respectively) with the
31 * GC_pthread_create and GC_CreateThread functions.
32 */
33
34 #include <ecl.h>
35
36 #ifdef _MSC_VER
37 #define sleep(x) Sleep((x)*1000)
38 #endif
39
40 static DWORD WINAPI
41 thread_entry_point(void *data)
42 {
43 cl_object form = (cl_object)data;
44
45 /*
46 * This is the entry point of the threads we have created.
47 * These threads have no valid lisp environment. The following
48 * routine initializes the lisp and makes it ready for working
49 * in this thread.
50 */
51
52 ecl_import_current_thread(ECL_NIL, ECL_NIL);
53
54 /*
55 * Here we execute some lisp code code.
56 */
57 cl_eval(form);
58
59 /*
60 * Finally, when we exit the thread we have to release the
61 * resources allocated by the lisp environment.
62 */
63 ecl_release_current_thread();
64
65 return 1;
66 }
67
68
69 int main(int narg, char **argv)
70 {
71 HANDLE code;
72 DWORD child_thread;
73 int i;
74 cl_object sym_print;
75
76 /*
77 * First of all, we have to initialize the ECL environment.
78 * This should be done from the main thread.
79 */
80 cl_boot(narg, argv);
81
82 /*
83 * Here we spawn 10 threads using the OS functions. The
84 * current version is for Unix and uses pthread_create.
85 * Since we have included <gc.h>, pthread_create will be
86 * replaced with the appropriate routine from the garbage
87 * collector.
88 */
89 sym_print = c_string_to_object("PRINT");
90 for (i = 0; i < 10; i++) {
91 cl_object form = cl_list(2, sym_print, MAKE_FIXNUM(i));
92 code = (HANDLE)CreateThread(NULL, 0, thread_entry_point, form, 0,
93 &child_thread);
94 if (code == NULL) {
95 printf("Unable to create thread. Code: %d\n", GetLastError());
96 exit(1);
97 }
98 }
99
100 /*
101 * Here we wait for the last thread to finish.
102 */
103 sleep(10);
104
105 return 0;
106 }