2 * collection.c: Garbage collection for handles
5 * Dick Porter (dick@ximian.com)
7 * (C) 2004 Novell, Inc.
14 #include <sys/types.h>
17 #include <mono/io-layer/wapi.h>
18 #include <mono/io-layer/collection.h>
19 #include <mono/io-layer/handles-private.h>
23 static pthread_t collection_thread_id;
25 static gpointer collection_thread (gpointer args) G_GNUC_NORETURN;
26 static gpointer collection_thread (gpointer unused G_GNUC_UNUSED)
28 struct timespec sleepytime;
30 sleepytime.tv_sec = _WAPI_HANDLE_COLLECTION_UPDATE_INTERVAL;
31 sleepytime.tv_nsec = 0;
34 //_wapi_handle_dump ();
35 _wapi_handle_update_refs ();
37 /* This is an abuse of the collection thread, but it's
38 * better than creating a new thread just for one more
41 _wapi_process_reap ();
43 nanosleep (&sleepytime, NULL);
47 /* Even though we tell gcc that this function doesn't return,
48 * other compilers won't see that.
54 void _wapi_collection_init (void)
59 ret = pthread_attr_init (&attr);
62 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
64 ret = pthread_attr_setstacksize (&attr, 65536);
66 ret = pthread_attr_setstacksize (&attr, PTHREAD_STACK_MIN);
71 ret = pthread_create (&collection_thread_id, &attr, collection_thread,
74 g_error ("%s: Couldn't create handle collection thread: %s",
75 __func__, g_strerror (ret));
79 void _wapi_handle_collect (void)
81 guint32 count = _wapi_shared_layout->collection_count;
85 g_message ("%s: (%d) Starting a collection", __func__, getpid ());
88 /* Become the collection master */
89 thr_ret = _wapi_handle_lock_shared_handles ();
90 g_assert (thr_ret == 0);
93 g_message ("%s: (%d) Master set", __func__, getpid ());
96 /* If count has changed, someone else jumped in as master */
97 if (count == _wapi_shared_layout->collection_count) {
98 guint32 too_old = (guint32)(time(NULL) & 0xFFFFFFFF) - _WAPI_HANDLE_COLLECTION_EXPIRED_INTERVAL;
100 for (i = 0; i < _WAPI_HANDLE_INITIAL_COUNT; i++) {
101 struct _WapiHandleShared *data;
103 data = &_wapi_shared_layout->handles[i];
104 if (data->timestamp < too_old) {
106 g_message ("%s: (%d) Deleting handle 0x%x", __func__, getpid (), i);
108 memset (&_wapi_shared_layout->handles[i], '\0', sizeof(struct _WapiHandleShared));
112 for (i = 0; i < _wapi_fileshare_layout->hwm; i++) {
113 struct _WapiFileShare *file_share = &_wapi_fileshare_layout->share_info[i];
115 if (file_share->timestamp < too_old) {
116 memset (file_share, '\0',
117 sizeof(struct _WapiFileShare));
121 InterlockedIncrement (&_wapi_shared_layout->collection_count);
124 _wapi_handle_unlock_shared_handles ();
127 g_message ("%s: (%d) Collection done", __func__, getpid ());