summaryrefslogtreecommitdiff
path: root/legacy/ecore/src/lib/ecore/ecore_thread.c
blob: 49c49f895a3979b92b0f9bb24e9f8a3c08a22420 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

#include <sys/time.h>

#ifdef HAVE_EVIL
# include <Evil.h>
#endif

#include "Ecore.h"
#include "ecore_private.h"

#ifdef EFL_HAVE_THREADS

# ifdef EFL_HAVE_POSIX_THREADS
#  include <pthread.h>
#  ifdef __linux__
#   include <sched.h>
#   include <sys/resource.h>
#   include <unistd.h>
#   include <sys/syscall.h>
#   include <errno.h>
#  endif

#  define PH(x)        pthread_t x
#  define PHE(x, y)    pthread_equal(x, y)
#  define PHS()        pthread_self()
#  define PHC(x, f, d) pthread_create(&(x), NULL, (void*) f, d)
#  define PHJ(x, p)    pthread_join(x, (void**)(&(p)))
#  define PHA(x)       pthread_cancel(x)

#  define CD(x)  pthread_cond_t x
#  define CDI(x) pthread_cond_init(&(x), NULL);
#  define CDD(x) pthread_cond_destroy(&(x));
#  define CDB(x) pthread_cond_broadcast(&(x));
#  define CDW(x, y, t) pthread_cond_timedwait(&(x), &(y), t);

#  define LK(x)  pthread_mutex_t x
#  define LKI(x) pthread_mutex_init(&(x), NULL);
#  define LKD(x) pthread_mutex_destroy(&(x));
#  define LKL(x) pthread_mutex_lock(&(x));
#  define LKU(x) pthread_mutex_unlock(&(x));

#  define LRWK(x)   pthread_rwlock_t x
#  define LRWKI(x)  pthread_rwlock_init(&(x), NULL);
#  define LRWKD(x)  pthread_rwlock_destroy(&(x));
#  define LRWKWL(x) pthread_rwlock_wrlock(&(x));
#  define LRWKRL(x) pthread_rwlock_rdlock(&(x));
#  define LRWKU(x)  pthread_rwlock_unlock(&(x));

# else /* EFL_HAVE_WIN32_THREADS */

#  define WIN32_LEAN_AND_MEAN
#  include <windows.h>
#  undef WIN32_LEAN_AND_MEAN

typedef struct
{
  HANDLE thread;
  void *val;
} win32_thread;

#  define PH(x)        win32_thread *x
#  define PHE(x, y)    ((x) == (y))
#  define PHS()        (HANDLE)GetCurrentThreadId()

int _ecore_thread_win32_create(win32_thread **x, LPTHREAD_START_ROUTINE f, void *d)
{
  win32_thread *t;
  t = (win32_thread *)calloc(1, sizeof(win32_thread));
  if (!t)
    return -1;

  (t)->thread = CreateThread(NULL, 0, f, d, 0, NULL);
  if (!t->thread)
    {
      free(t);
      return -1;
    }
  t->val = d;
  *x = t;

  return 0;
}
#  define PHC(x, f, d) _ecore_thread_win32_create(&(x), (LPTHREAD_START_ROUTINE)f, d)

int _ecore_thread_win32_join(win32_thread *x, void **res)
{
  if (!PHE(x, PHS()))
    {
      WaitForSingleObject(x->thread, INFINITE);
      CloseHandle(x->thread);
    }
  if (res) *res = x->val;

  return 0;
}

#  define PHJ(x, p) _ecore_thread_win32_join(x, (void**)(&(p)))
#  define PHA(x) TerminateThread(x->thread, 0)

#  define LK(x)  HANDLE x
#  define LKI(x) x = CreateMutex(NULL, FALSE, NULL)
#  define LKD(x) CloseHandle(x)
#  define LKL(x) WaitForSingleObject(x, INFINITE)
#  define LKU(x) ReleaseMutex(x)

typedef struct
{
  HANDLE semaphore;
  LONG threads_count;
  CRITICAL_SECTION threads_count_lock;
} win32_cond;

#  define CD(x)  win32_cond *x

#  define CDI(x)                                                     \
   do {                                                              \
     x = (win32_cond *)calloc(1, sizeof(win32_cond));                \
     if (x)                                                          \
        {                                                            \
          x->semaphore = CreateSemaphore(NULL, 0, 0x7fffffff, NULL); \
          if (x->semaphore)                                          \
            InitializeCriticalSection(&x->threads_count_lock);     \
          else                                                       \
            {                                                        \
              free(x);                                               \
              x = NULL;                                              \
            }                                                        \
        }                                                            \
   } while (0)

#  define CDD(x)               \
  do {                         \
    CloseHandle(x->semaphore); \
    free(x);                   \
    x = NULL;                  \
   } while (0)

#  define CDB(x)                                            \
do {                                                        \
  EnterCriticalSection(&x->threads_count_lock);             \
  if (x->threads_count > 0)                                 \
    ReleaseSemaphore(x->semaphore, x->threads_count, NULL); \
  LeaveCriticalSection (&x->threads_count_lock);            \
 } while (0)

int _ecore_thread_win32_cond_timedwait(win32_cond *c, HANDLE *external_mutex, struct timeval *t)
{
  DWORD res;
  DWORD val = t->tv_sec * 1000 + (t->tv_usec / 1000);
  LKL(external_mutex);
  EnterCriticalSection (&c->threads_count_lock);
  c->threads_count++;
  LeaveCriticalSection (&c->threads_count_lock);
  LKU(external_mutex);
  res = WaitForSingleObject(c->semaphore, val);
  if (res == WAIT_OBJECT_0)
    return 0;
  else
    return -1;
}
#  define CDW(x, y, t) _ecore_thread_win32_cond_timedwait(x, y, t)

typedef struct
{
  LONG readers_count;
  LONG writers_count;
  int readers;
  int writers; 
  LK(mutex);
  CD(cond_read);
  CD(cond_write);
} win32_rwl;

#  define LRWK(x)   win32_rwl *x
#  define LRWKI(x)                                 \
  do {                                             \
    x = (win32_rwl *)calloc(1, sizeof(win32_rwl)); \
    if (x)                                         \
      {                                            \
        LKI(x->mutex);                             \
        if (x->mutex)                              \
          {                                        \
            CDI(x->cond_read);                     \
            if (x->cond_read)                      \
              {                                    \
                CDI(x->cond_write);                \
                if (!x->cond_write)                \
                  {                                \
                    CDD(x->cond_read);             \
                    LKD(x->mutex);                 \
                    free(x);                       \
                    x = NULL;                      \
                  }                                \
              }                                    \
            else                                   \
              {                                    \
                LKD(x->mutex);                     \
                free(x);                           \
                x = NULL;                          \
              }                                    \
          }                                        \
        else                                       \
          {                                        \
            free(x);                               \
            x = NULL;                              \
          }                                        \
      }                                            \
  } while (0)

#  define LRWKD(x)                   \
  do {                               \
    LKU(x->mutex);                   \
    LKD(x->mutex);                   \
    CDD(x->cond_write);              \
    CDD(x->cond_read);               \
    free(x);                         \
  } while (0)
#  define LRWKWL(x)                                                       \
  do {                                                                    \
    DWORD res;                                                            \
    LKU(x->mutex);                                                        \
    if (x->writers || x->readers > 0)                                     \
      {                                                                   \
        x->writers_count++;                                               \
        while (x->writers || x->readers > 0)                              \
          {                                                               \
            EnterCriticalSection(&x->cond_write->threads_count_lock);     \
            x->cond_read->threads_count++;                                \
            LeaveCriticalSection(&x->cond_write->threads_count_lock);     \
            res = WaitForSingleObject(x->cond_write->semaphore, INFINITE); \
            if (res != WAIT_OBJECT_0) break;                              \
          }                                                               \
        x->writers_count--;                                               \
      }                                                                   \
    if (res == 0) x->writers_count = 1;                                   \
    LKU(x->mutex);                                                        \
  } while (0)
#  define LRWKRL(x)                                                       \
  do {                                                                    \
    DWORD res;                                                            \
    LKL(x->mutex);                                                        \
    if (x->writers)                                                       \
      {                                                                   \
        x->readers_count++;                                               \
        while (x->writers)                                                \
          {                                                               \
            EnterCriticalSection(&x->cond_write->threads_count_lock);     \
            x->cond_read->threads_count++;                                \
            LeaveCriticalSection(&x->cond_write->threads_count_lock);     \
            res = WaitForSingleObject(x->cond_write->semaphore, INFINITE); \
            if (res != WAIT_OBJECT_0) break;                              \
          }                                                               \
        x->readers_count--;                                               \
      }                                                                   \
    if (res == 0)                                                         \
      x->readers++;                                                       \
    LKU(x->mutex);                                                        \
  } while (0)
#  define LRWKU(x)                                                     \
  do {                                                                 \
    LKL(x->mutex);                                                     \
    if (x->writers)                                                    \
      {                                                                \
        x->writers = 0;                                                \
        if (x->readers_count == 1)                                     \
          {                                                            \
            EnterCriticalSection(&x->cond_read->threads_count_lock);   \
            if (x->cond_read->threads_count > 0)                       \
              ReleaseSemaphore(x->cond_read->semaphore, 1, 0);         \
            LeaveCriticalSection(&x->cond_read->threads_count_lock);   \
          }                                                            \
        else if (x->readers_count > 0)                                 \
          CDB(x->cond_read);                                           \
        else if (x->writers_count > 0)                                 \
          {                                                            \
            EnterCriticalSection (&x->cond_write->threads_count_lock); \
            if (x->cond_write->threads_count > 0)                      \
              ReleaseSemaphore(x->cond_write->semaphore, 1, 0);        \
            LeaveCriticalSection (&x->cond_write->threads_count_lock); \
          }                                                            \
      }                                                                \
    else if (x->readers > 0)                                           \
      {                                                                \
        x->readers--;                                                  \
        if (x->readers == 0 && x->writers_count > 0)                   \
          {                                                            \
            EnterCriticalSection (&x->cond_write->threads_count_lock); \
            if (x->cond_write->threads_count > 0)                      \
              ReleaseSemaphore(x->cond_write->semaphore, 1, 0);        \
            LeaveCriticalSection (&x->cond_write->threads_count_lock); \
          }                                                            \
      }                                                                \
    LKU(x->mutex);                                                     \
  } while (0)

# endif

#endif

typedef struct _Ecore_Pthread_Worker Ecore_Pthread_Worker;
typedef struct _Ecore_Pthread Ecore_Pthread;
typedef struct _Ecore_Thread_Data  Ecore_Thread_Data;

struct _Ecore_Thread_Data
{
   void *data;
   Eina_Free_Cb cb;
};

struct _Ecore_Pthread_Worker
{
   union {
      struct {
         Ecore_Thread_Cb func_blocking;
      } short_run;
      struct {
         Ecore_Thread_Cb func_heavy;
         Ecore_Thread_Notify_Cb func_notify;
         Ecore_Pipe *notify;

         Ecore_Pipe *direct_pipe;
         Ecore_Pthread_Worker *direct_worker;

         int send;
         int received;
      } feedback_run;
   } u;

   Ecore_Thread_Cb func_cancel;
   Ecore_Thread_Cb func_end;
#ifdef EFL_HAVE_THREADS
   PH(self);
   Eina_Hash *hash;
   CD(cond);
   LK(mutex);
#endif

   const void *data;

   Eina_Bool cancel : 1;
   Eina_Bool feedback_run : 1;
   Eina_Bool kill : 1;
};

#ifdef EFL_HAVE_THREADS
typedef struct _Ecore_Pthread_Data Ecore_Pthread_Data;

struct _Ecore_Pthread_Data
{
   Ecore_Pthread_Worker *death_job;
   Ecore_Pipe *p;
   void *data;
   PH(thread);
};
#endif

static void _ecore_thread_handler(void *data __UNUSED__, void *buffer, unsigned int nbyte);

static int _ecore_thread_count_max = 0;
static int ECORE_THREAD_PIPE_DEL = 0;
static Eina_Array *_ecore_thread_pipe = NULL;

static Ecore_Pipe*
_ecore_thread_pipe_get(void)
{
   if (eina_array_count_get(_ecore_thread_pipe) > 0)
     return eina_array_pop(_ecore_thread_pipe);

   return ecore_pipe_add(_ecore_thread_handler, NULL);
}

#ifdef EFL_HAVE_THREADS
static int _ecore_thread_count = 0;

static Ecore_Event_Handler *del_handler = NULL;
static Eina_List *_ecore_active_job_threads = NULL;
static Eina_List *_ecore_pending_job_threads = NULL;
static Eina_List *_ecore_pending_job_threads_feedback = NULL;
static LK(_ecore_pending_job_threads_mutex);

static Eina_Hash *_ecore_thread_global_hash = NULL;
static LRWK(_ecore_thread_global_hash_lock);
static LK(_ecore_thread_global_hash_mutex);
static CD(_ecore_thread_global_hash_cond);

static PH(main_loop_thread);
static Eina_Bool have_main_loop_thread = 0;

static Eina_Trash *_ecore_thread_worker_trash = NULL;
static int _ecore_thread_worker_count = 0;

static void
_ecore_thread_worker_free(Ecore_Pthread_Worker *worker)
{
   if (_ecore_thread_worker_count > (_ecore_thread_count_max + 1) * 16)
     {
        free(worker);
        return ;
     }

   eina_trash_push(&_ecore_thread_worker_trash, worker);
}

static void
_ecore_thread_data_free(void *data)
{
   Ecore_Thread_Data *d = data;

   if (d->cb) d->cb(d->data);
   free(d);
}

static void
_ecore_thread_pipe_free(void *data __UNUSED__, void *event)
{
   Ecore_Pipe *p = event;

   eina_array_push(_ecore_thread_pipe, p);
   eina_threads_shutdown();
}

static Eina_Bool
_ecore_thread_pipe_del(void *data __UNUSED__, int type __UNUSED__, void *event __UNUSED__)
{
   /* This is a hack to delay pipe destruction until we are out of its internal loop. */
   return ECORE_CALLBACK_CANCEL;
}

static void
_ecore_thread_end(Ecore_Pthread_Data *pth, __UNUSED__ Ecore_Thread *work)
{
   Ecore_Pipe *p;

   if (PHJ(pth->thread, p) != 0)
     return ;

   _ecore_active_job_threads = eina_list_remove(_ecore_active_job_threads, pth);

   ecore_event_add(ECORE_THREAD_PIPE_DEL, pth->p, _ecore_thread_pipe_free, NULL);
   free(pth);
}

static void
_ecore_thread_kill(Ecore_Pthread_Worker *work)
{
   if (work->cancel)
     {
        if (work->func_cancel)
          work->func_cancel((void *) work->data, (Ecore_Thread *) work);
     }
   else
     {
        if (work->func_end)
          work->func_end((void *) work->data, (Ecore_Thread *) work);
     }

   if (work->feedback_run)
     {
        ecore_pipe_del(work->u.feedback_run.notify);

        if (work->u.feedback_run.direct_pipe)
          eina_array_push(_ecore_thread_pipe, work->u.feedback_run.direct_pipe);
        if (work->u.feedback_run.direct_worker)
          _ecore_thread_worker_free(work->u.feedback_run.direct_worker);
     }
   CDD(work->cond);
   LKD(work->mutex);
   if (work->hash)
     eina_hash_free(work->hash);
   free(work);
}

static void
_ecore_thread_handler(void *data __UNUSED__, void *buffer, unsigned int nbyte)
{
   Ecore_Pthread_Worker *work;

   if (nbyte != sizeof (Ecore_Pthread_Worker *)) return ;

   work = *(Ecore_Pthread_Worker **)buffer;

   if (work->feedback_run)
     {
        if (work->u.feedback_run.send != work->u.feedback_run.received)
          {
             work->kill = EINA_TRUE;
             return ;
          }
     }

   _ecore_thread_kill(work);
}

static void
_ecore_notify_handler(void *data, void *buffer, unsigned int nbyte)
{
   Ecore_Pthread_Worker *work = data;
   void *user_data;

   if (nbyte != sizeof (Ecore_Pthread_Worker *)) return ;

   user_data = *(void **)buffer;
   work->u.feedback_run.received++;

   if (work->u.feedback_run.func_notify)
     work->u.feedback_run.func_notify((void *) work->data, (Ecore_Thread *) work, user_data);

   /* Force reading all notify event before killing the thread */
   if (work->kill && work->u.feedback_run.send == work->u.feedback_run.received)
     {
        _ecore_thread_kill(work);
     }
}

static void
_ecore_short_job(Ecore_Pipe *end_pipe)
{
   Ecore_Pthread_Worker *work;

   while (_ecore_pending_job_threads)
     {
        LKL(_ecore_pending_job_threads_mutex);

        if (!_ecore_pending_job_threads)
          {
             LKU(_ecore_pending_job_threads_mutex);
             break;
          }

        work = eina_list_data_get(_ecore_pending_job_threads);
        _ecore_pending_job_threads = eina_list_remove_list(_ecore_pending_job_threads,
                                                           _ecore_pending_job_threads);

        LKU(_ecore_pending_job_threads_mutex);

        if (!work->cancel)
          work->u.short_run.func_blocking((void *) work->data, (Ecore_Thread*) work);

        ecore_pipe_write(end_pipe, &work, sizeof (Ecore_Pthread_Worker *));
     }
}

static void
_ecore_feedback_job(Ecore_Pipe *end_pipe, PH(thread))
{
   Ecore_Pthread_Worker *work;

   while (_ecore_pending_job_threads_feedback)
     {
        LKL(_ecore_pending_job_threads_mutex);

        if (!_ecore_pending_job_threads_feedback)
          {
             LKU(_ecore_pending_job_threads_mutex);
             break;
          }

        work = eina_list_data_get(_ecore_pending_job_threads_feedback);
        _ecore_pending_job_threads_feedback = eina_list_remove_list(_ecore_pending_job_threads_feedback,
                                                                    _ecore_pending_job_threads_feedback);

        LKU(_ecore_pending_job_threads_mutex);

        work->self = thread;
        if (!work->cancel)
          work->u.feedback_run.func_heavy((void *) work->data, (Ecore_Thread *) work);

        ecore_pipe_write(end_pipe, &work, sizeof (Ecore_Pthread_Worker *));
     }
}

static void *
_ecore_direct_worker(Ecore_Pthread_Worker *work)
{
   Ecore_Pthread_Data *pth;

#ifdef EFL_POSIX_THREADS
   pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
   pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
#endif

   eina_sched_prio_drop();

   pth = malloc(sizeof (Ecore_Pthread_Data));
   if (!pth) return NULL;

   pth->p = work->u.feedback_run.direct_pipe;
   if (!pth->p)
     {
        free(pth);
        return NULL;
     }
   pth->thread = PHS();

   work->self = pth->thread;
   work->u.feedback_run.func_heavy((void *) work->data, (Ecore_Thread *) work);

   ecore_pipe_write(pth->p, &work, sizeof (Ecore_Pthread_Worker *));

   work = work->u.feedback_run.direct_worker;
   if (!work)
     {
        free(pth);
        return NULL;
     }

   work->data = pth;
   work->u.short_run.func_blocking = NULL;
   work->func_end = (void *) _ecore_thread_end;
   work->func_cancel = NULL;
   work->cancel = EINA_FALSE;
   work->feedback_run = EINA_FALSE;
   work->kill = EINA_FALSE;
   work->hash = NULL;
   CDI(work->cond);
   LKI(work->mutex);

   ecore_pipe_write(pth->p, &work, sizeof (Ecore_Pthread_Worker *));

   return pth->p;
}

static void *
_ecore_thread_worker(Ecore_Pthread_Data *pth)
{
   Ecore_Pthread_Worker *work;

#ifdef EFL_POSIX_THREADS
   pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
   pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
#endif

   eina_sched_prio_drop();

   LKL(_ecore_pending_job_threads_mutex);
   _ecore_thread_count++;
   LKU(_ecore_pending_job_threads_mutex);

 restart:
   if (_ecore_pending_job_threads) _ecore_short_job(pth->p);
   if (_ecore_pending_job_threads_feedback) _ecore_feedback_job(pth->p, pth->thread);

   /* FIXME: Check if there is feedback running task todo, and switch to feedback run handler. */

   LKL(_ecore_pending_job_threads_mutex);
   if (_ecore_pending_job_threads || _ecore_pending_job_threads_feedback)
     {
        LKU(_ecore_pending_job_threads_mutex);
        goto restart;
     }
   LKU(_ecore_pending_job_threads_mutex);

   /* Sleep a little to prevent premature death */
   usleep(200);

   LKL(_ecore_pending_job_threads_mutex);
   if (_ecore_pending_job_threads || _ecore_pending_job_threads_feedback)
     {
        LKU(_ecore_pending_job_threads_mutex);
        goto restart;
     }
   _ecore_thread_count--;
   LKU(_ecore_pending_job_threads_mutex);

   work = pth->death_job;
   if (!work) return NULL;

   work->data = pth;
   work->u.short_run.func_blocking = NULL;
   work->func_end = (void *) _ecore_thread_end;
   work->func_cancel = NULL;
   work->cancel = EINA_FALSE;
   work->feedback_run = EINA_FALSE;
   work->kill = EINA_FALSE;
   work->hash = NULL;
   CDI(work->cond);
   LKI(work->mutex);

   ecore_pipe_write(pth->p, &work, sizeof (Ecore_Pthread_Worker *));

   return pth->p;
}

#endif

static Ecore_Pthread_Worker *
_ecore_thread_worker_new(void)
{
   Ecore_Pthread_Worker *result;

#ifdef EFL_HAVE_THREADS
   result = eina_trash_pop(&_ecore_thread_worker_trash);

   if (!result) result = malloc(sizeof (Ecore_Pthread_Worker));
   else _ecore_thread_worker_count--;

   return result;
#else
   return malloc(sizeof (Ecore_Pthread_Worker));
#endif
}

void
_ecore_thread_init(void)
{
   _ecore_thread_count_max = eina_cpu_count();
   if (_ecore_thread_count_max <= 0)
     _ecore_thread_count_max = 1;

   ECORE_THREAD_PIPE_DEL = ecore_event_type_new();
   _ecore_thread_pipe = eina_array_new(8);

#ifdef EFL_HAVE_THREADS
   del_handler = ecore_event_handler_add(ECORE_THREAD_PIPE_DEL, _ecore_thread_pipe_del, NULL);
   main_loop_thread = PHS();
   have_main_loop_thread = 1;

   LKI(_ecore_pending_job_threads_mutex);
   LRWKI(_ecore_thread_global_hash_lock);
   LKI(_ecore_thread_global_hash_mutex);
   CDI(_ecore_thread_global_hash_cond);
#endif
}

void
_ecore_thread_shutdown(void)
{
   /* FIXME: If function are still running in the background, should we kill them ? */
   Ecore_Pipe *p;
   Eina_Array_Iterator it;
   unsigned int i;

#ifdef EFL_HAVE_THREADS
   Ecore_Pthread_Worker *work;
   Ecore_Pthread_Data *pth;

   LKL(_ecore_pending_job_threads_mutex);

   EINA_LIST_FREE(_ecore_pending_job_threads, work)
     {
        if (work->func_cancel)
          work->func_cancel((void *)work->data, (Ecore_Thread *) work);
        free(work);
     }

   EINA_LIST_FREE(_ecore_pending_job_threads_feedback, work)
     {
        if (work->func_cancel)
          work->func_cancel((void *)work->data, (Ecore_Thread *) work);
        free(work);
     }

   LKU(_ecore_pending_job_threads_mutex);

   /* Improve emergency shutdown */
   EINA_LIST_FREE(_ecore_active_job_threads, pth)
     {
        Ecore_Pipe *p;

        PHA(pth->thread);
        PHJ(pth->thread, p);

        ecore_pipe_del(pth->p);
     }
   if (_ecore_thread_global_hash)
     eina_hash_free(_ecore_thread_global_hash);
   ecore_event_handler_del(del_handler);
   have_main_loop_thread = 0;
   del_handler = NULL;

   LKD(_ecore_pending_job_threads_mutex);
   LRWKD(_ecore_thread_global_hash_lock);
   LKD(_ecore_thread_global_hash_mutex);
   CDD(_ecore_thread_global_hash_cond);
#endif

   EINA_ARRAY_ITER_NEXT(_ecore_thread_pipe, i, p, it)
     ecore_pipe_del(p);

   eina_array_free(_ecore_thread_pipe);
   _ecore_thread_pipe = NULL;
}

/**
 * @addtogroup Ecore_Group Ecore - Main Loop and Job Functions.
 *
 * @{
 */

/**
 * @addtogroup Ecore_Thread_Group Ecore Thread functions
 *
 * These functions allow for ecore-managed threads which integrate with ecore's main loop.
 *
 * @{
 */

/**
 * @brief Run some blocking code in a parallel thread to avoid locking the main loop.
 * @param func_blocking The function that should run in another thread.
 * @param func_end The function that will be called in the main loop if the thread terminate correctly.
 * @param func_cancel The function that will be called in the main loop if the thread is cancelled.
 * @param data User context data to pass to all callback.
 * @return A reference to the newly created thread instance, or NULL if it failed.
 *
 * ecore_thread_run provide a facility for easily managing blocking task in a
 * parallel thread. You should provide three function. The first one, func_blocking,
 * that will do the blocking work in another thread (so you should not use the
 * EFL in it except Eina if you are careful). The second one, func_end,
 * that will be called in Ecore main loop when func_blocking is done. So you
 * can use all the EFL inside this function. The last one, func_cancel, will
 * be called in the main loop if the thread is cancelled or could not run at all.
 *
 * Be aware, that you can't make assumption on the result order of func_end
 * after many call to ecore_thread_run, as we start as much thread as the
 * host CPU can handle.
 */
EAPI Ecore_Thread *
ecore_thread_run(Ecore_Thread_Cb func_blocking,
                 Ecore_Thread_Cb func_end,
                 Ecore_Thread_Cb func_cancel,
                 const void *data)
{
   Ecore_Pthread_Worker *work;
#ifdef EFL_HAVE_THREADS
   Ecore_Pthread_Data *pth = NULL;
#endif

   if (!func_blocking) return NULL;

   work = _ecore_thread_worker_new();
   if (!work)
     {
        if (func_cancel)
          func_cancel((void *) data, NULL);
        return NULL;
     }

   work->u.short_run.func_blocking = func_blocking;
   work->func_end = func_end;
   work->func_cancel = func_cancel;
   work->cancel = EINA_FALSE;
   work->feedback_run = EINA_FALSE;
   work->kill = EINA_FALSE;
   work->data = data;

#ifdef EFL_HAVE_THREADS
   work->hash = NULL;
   CDI(work->cond);
   LKI(work->mutex);

   LKL(_ecore_pending_job_threads_mutex);
   _ecore_pending_job_threads = eina_list_append(_ecore_pending_job_threads, work);

   if (_ecore_thread_count == _ecore_thread_count_max)
     {
        LKU(_ecore_pending_job_threads_mutex);
        return (Ecore_Thread *) work;
     }

   LKU(_ecore_pending_job_threads_mutex);

   /* One more thread could be created. */
   pth = malloc(sizeof (Ecore_Pthread_Data));
   if (!pth) goto on_error;

   pth->p = _ecore_thread_pipe_get();
   pth->death_job = _ecore_thread_worker_new();
   if (!pth->p || !pth->death_job) goto on_error;

   eina_threads_init();

   if (PHC(pth->thread, _ecore_thread_worker, pth) == 0)
      return (Ecore_Thread *) work;

   eina_threads_shutdown();

 on_error:
   if (pth)
     {
        if (pth->p) eina_array_push(_ecore_thread_pipe, pth->p);
        if (pth->death_job) _ecore_thread_worker_free(pth->death_job);
        free(pth);
     }

   if (_ecore_thread_count == 0)
     {
        LKL(_ecore_pending_job_threads_mutex);
        _ecore_pending_job_threads = eina_list_remove(_ecore_pending_job_threads, work);
        LKU(_ecore_pending_job_threads_mutex);

        if (work->func_cancel)
          work->func_cancel((void *) work->data, (Ecore_Thread *) work);
        free(work);
        work = NULL;
     }
   return (Ecore_Thread *) work;
#else
   /*
     If no thread and as we don't want to break app that rely on this
     facility, we will lock the interface until we are done.
    */
   func_blocking((void *)data, (Ecore_Thread *) work);
   if (work->cancel == EINA_FALSE) func_end((void *)data, (Ecore_Thread *) work);
   else func_end((void *)data, (Ecore_Thread *) work);

   free(work);

   return NULL;
#endif
}

/**
 * @brief Cancel a running thread.
 * @param thread The thread to cancel.
 * @return Will return EINA_TRUE if the thread has been cancelled,
 *         EINA_FALSE if it is pending.
 *
 * ecore_thread_cancel give the possibility to cancel a task still running. It
 * will return EINA_FALSE, if the destruction is delayed or EINA_TRUE if it is
 * cancelled after this call.
 *
 * This function work in the main loop and in the thread, but you should not pass
 * the Ecore_Thread variable from main loop to the worker thread in any structure.
 * You should always use the one passed to the Ecore_Thread_Heavy_Cb.
 *
 * func_end, func_cancel will destroy the handler, so don't use it after.
 * And if ecore_thread_cancel return EINA_TRUE, you should not use Ecore_Thread also.
 */
EAPI Eina_Bool
ecore_thread_cancel(Ecore_Thread *thread)
{
#ifdef EFL_HAVE_THREADS
   Ecore_Pthread_Worker *work = (Ecore_Pthread_Worker *)thread;
   Eina_List *l;

   if (!work)
     return EINA_TRUE;
   if (work->cancel)
     return EINA_FALSE;

   if (work->feedback_run)
     {
        if (work->kill)
          return EINA_TRUE;
        if (work->u.feedback_run.send != work->u.feedback_run.received)
          goto on_exit;
     }

   LKL(_ecore_pending_job_threads_mutex);

   if ((have_main_loop_thread) &&
       (PHE(main_loop_thread, PHS())))
     {
        if (!work->feedback_run)
          EINA_LIST_FOREACH(_ecore_pending_job_threads, l, work)
            {
               if ((void *) work == (void *) thread)
                 {
                    _ecore_pending_job_threads = eina_list_remove_list(_ecore_pending_job_threads, l);

                    LKU(_ecore_pending_job_threads_mutex);

                    if (work->func_cancel)
                      work->func_cancel((void *) work->data, (Ecore_Thread *) work);
                    free(work);

                    return EINA_TRUE;
                 }
            }
        else
          EINA_LIST_FOREACH(_ecore_pending_job_threads_feedback, l, work)
            {
               if ((void *) work == (void *) thread)
                 {
                    _ecore_pending_job_threads_feedback = eina_list_remove_list(_ecore_pending_job_threads_feedback, l);

                    LKU(_ecore_pending_job_threads_mutex);

                    if (work->func_cancel)
                      work->func_cancel((void *) work->data, (Ecore_Thread *) work);
                    free(work);

                    return EINA_TRUE;
                 }
            }
     }

   LKU(_ecore_pending_job_threads_mutex);

   /* Delay the destruction */
 on_exit:
   ((Ecore_Pthread_Worker *)thread)->cancel = EINA_TRUE;
   return EINA_FALSE;
#else
   return EINA_TRUE;
#endif
}

/**
 * @brief Tell if a thread was canceled or not.
 * @param thread The thread to test.
 * @return EINA_TRUE if the thread is cancelled,
 *         EINA_FALSE if it is not.
 *
 * You can use this function in main loop and in the thread.
 */
EAPI Eina_Bool
ecore_thread_check(Ecore_Thread *thread)
{
   Ecore_Pthread_Worker *worker = (Ecore_Pthread_Worker *) thread;

   if (!worker) return EINA_TRUE;
   return worker->cancel;
}

/**
 * @brief Run some heavy code in a parallel thread to avoid locking the main loop.
 * @param func_heavy The function that should run in another thread.
 * @param func_notify The function that will receive the data send by func_heavy in the main loop.
 * @param func_end The function that will be called in the main loop if the thread terminate correctly.
 * @param func_cancel The function that will be called in the main loop if the thread is cancelled.
 * @param data User context data to pass to all callback.
 * @param try_no_queue If you want to run outside of the thread pool.
 * @return A reference to the newly created thread instance, or NULL if it failed.
 *
 * ecore_thread_feedback_run provide a facility for easily managing heavy task in a
 * parallel thread. You should provide four functions. The first one, func_heavy,
 * that will do the heavy work in another thread (so you should not use the
 * EFL in it except Eina and Eet if you are careful). The second one, func_notify,
 * will receive the data send from the thread function (func_heavy) by ecore_thread_notify
 * in the main loop (and so, can use all the EFL). Tje third, func_end,
 * that will be called in Ecore main loop when func_heavy is done. So you
 * can use all the EFL inside this function. The last one, func_cancel, will
 * be called in the main loop also, if the thread is cancelled or could not run at all.
 *
 * Be aware, that you can't make assumption on the result order of func_end
 * after many call to ecore_feedback_run, as we start as much thread as the
 * host CPU can handle.
 *
 * If you set try_no_queue, it will try to run outside of the thread pool, this can bring
 * the CPU down, so be careful with that. Of course if it can't start a new thread, it will
 * try to use one from the pool.
 */
EAPI Ecore_Thread *ecore_thread_feedback_run(Ecore_Thread_Cb func_heavy,
                                             Ecore_Thread_Notify_Cb func_notify,
                                             Ecore_Thread_Cb func_end,
                                             Ecore_Thread_Cb func_cancel,
                                             const void *data,
                                             Eina_Bool try_no_queue)
{

#ifdef EFL_HAVE_THREADS
   Ecore_Pthread_Worker *worker;
   Ecore_Pthread_Data *pth = NULL;

   if (!func_heavy) return NULL;

   worker = _ecore_thread_worker_new();
   if (!worker) goto on_error;

   worker->u.feedback_run.func_heavy = func_heavy;
   worker->u.feedback_run.func_notify = func_notify;
   worker->hash = NULL;
   CDI(worker->cond);
   LKI(worker->mutex);
   worker->func_cancel = func_cancel;
   worker->func_end = func_end;
   worker->data = data;
   worker->cancel = EINA_FALSE;
   worker->feedback_run = EINA_TRUE;
   worker->kill = EINA_FALSE;
   worker->u.feedback_run.send = 0;
   worker->u.feedback_run.received = 0;

   worker->u.feedback_run.notify = ecore_pipe_add(_ecore_notify_handler, worker);
   worker->u.feedback_run.direct_pipe = NULL;
   worker->u.feedback_run.direct_worker = NULL;

   if (!try_no_queue)
     {
        PH(t);

        worker->u.feedback_run.direct_pipe = _ecore_thread_pipe_get();
        worker->u.feedback_run.direct_worker = _ecore_thread_worker_new();

        if (PHC(t, _ecore_direct_worker, worker) == 0)
           return (Ecore_Thread *) worker;
     }

   LKL(_ecore_pending_job_threads_mutex);
   _ecore_pending_job_threads_feedback = eina_list_append(_ecore_pending_job_threads_feedback, worker);

   if (_ecore_thread_count == _ecore_thread_count_max)
     {
        LKU(_ecore_pending_job_threads_mutex);
        return (Ecore_Thread *) worker;
     }

   LKU(_ecore_pending_job_threads_mutex);

   /* One more thread could be created. */
   pth = malloc(sizeof (Ecore_Pthread_Data));
   if (!pth) goto on_error;

   pth->p = _ecore_thread_pipe_get();
   pth->death_job = _ecore_thread_worker_new();
   if (!pth->p || !pth->death_job) goto on_error;

   eina_threads_init();

   if (PHC(pth->thread, _ecore_thread_worker, pth) == 0)
      return (Ecore_Thread *) worker;

   eina_threads_shutdown();

 on_error:
   if (pth)
     {
        if (pth->p) eina_array_push(_ecore_thread_pipe, pth->p);
        if (pth->death_job) _ecore_thread_worker_free(pth->death_job);
        free(pth);
     }

   if (_ecore_thread_count == 0)
     {
        LKL(_ecore_pending_job_threads_mutex);
        _ecore_pending_job_threads_feedback = eina_list_remove(_ecore_pending_job_threads_feedback,
                                                               worker);
        LKU(_ecore_pending_job_threads_mutex);

        if (func_cancel) func_cancel((void *) data, NULL);

        if (worker)
          {
             ecore_pipe_del(worker->u.feedback_run.notify);
             free(worker);
             worker = NULL;
          }
     }

   return (Ecore_Thread *) worker;
#else
   Ecore_Pthread_Worker worker;

   (void) try_no_queue;

   /*
     If no thread and as we don't want to break app that rely on this
     facility, we will lock the interface until we are done.
    */
   worker.u.feedback_run.func_heavy = func_heavy;
   worker.u.feedback_run.func_notify = func_notify;
   worker.u.feedback_run.notify = NULL;
   worker.u.feedback_run.send = 0;
   worker.u.feedback_run.received = 0;
   worker.func_cancel = func_cancel;
   worker.func_end = func_end;
   worker.data = data;
   worker.cancel = EINA_FALSE;
   worker.feedback_run = EINA_TRUE;
   worker.kill = EINA_FALSE;

   func_heavy((void *)data, (Ecore_Thread *) &worker);

   if (worker.cancel) func_cancel((void *)data, (Ecore_Thread *) &worker);
   else func_end((void *)data, (Ecore_Thread *) &worker);

   return NULL;
#endif
}

/**
 * @brief Send data to main loop from worker thread.
 * @param thread The current Ecore_Thread context to send data from
 * @param data Data to be transmitted to the main loop
 * @return EINA_TRUE if data was successfully send to main loop,
 *         EINA_FALSE if anything goes wrong.
 *
 * After a succesfull call, the data should be considered owned
 * by the main loop.
 *
 * You should use this function only in the func_heavy call.
 */
EAPI Eina_Bool
ecore_thread_feedback(Ecore_Thread *thread, const void *data)
{
   Ecore_Pthread_Worker *worker = (Ecore_Pthread_Worker *) thread;

   if (!worker) return EINA_FALSE;
   if (!worker->feedback_run) return EINA_FALSE;

#ifdef EFL_HAVE_THREADS
   if (!PHE(worker->self, PHS())) return EINA_FALSE;

   worker->u.feedback_run.send++;
   ecore_pipe_write(worker->u.feedback_run.notify, &data, sizeof (void *));

   return EINA_TRUE;
#else
   worker->u.feedback_run.func_notify((void*) worker->data, thread, (void*) data);

   return EINA_TRUE;
#endif
}

/**
 * @brief Get number of active thread jobs
 * @return Number of active threads running jobs
 * This returns the number of threads currently running jobs through the
 * ecore_thread api.
 */
EAPI int
ecore_thread_active_get(void)
{
#ifdef EFL_HAVE_THREADS
   return _ecore_thread_count;
#else
   return 0;
#endif
}

/**
 * @brief Get number of pending (short) thread jobs
 * @return Number of pending threads running "short" jobs
 * This returns the number of threads currently running jobs through the
 * ecore_thread_run api call.
 */
EAPI int
ecore_thread_pending_get(void)
{
   int ret;
#ifdef EFL_HAVE_THREADS
   LKL(_ecore_pending_job_threads_mutex);
   ret = eina_list_count(_ecore_pending_job_threads);
   LKU(_ecore_pending_job_threads_mutex);
   return ret;
#else
   return 0;
#endif
}

/**
 * @brief Get number of pending feedback thread jobs
 * @return Number of pending threads running "feedback" jobs
 * This returns the number of threads currently running jobs through the
 * ecore_thread_feedback_run api call.
 */
EAPI int
ecore_thread_pending_feedback_get(void)
{
   int ret;
#ifdef EFL_HAVE_THREADS
   LKL(_ecore_pending_job_threads_mutex);
   ret = eina_list_count(_ecore_pending_job_threads_feedback);
   LKU(_ecore_pending_job_threads_mutex);
   return ret;
#else
   return 0;
#endif
}

/**
 * @brief Get number of pending thread jobs
 * @return Number of pending threads running jobs
 * This returns the number of threads currently running jobs through the
 * ecore_thread_run and ecore_thread_feedback_run api calls combined.
 */
EAPI int
ecore_thread_pending_total_get(void)
{
   int ret;
#ifdef EFL_HAVE_THREADS
   LKL(_ecore_pending_job_threads_mutex);
   ret = eina_list_count(_ecore_pending_job_threads) + eina_list_count(_ecore_pending_job_threads_feedback);
   LKU(_ecore_pending_job_threads_mutex);
   return ret;
#else
   return 0;
#endif
}

/**
 * @brief Get the max number of threads that can run simultaneously
 * @return Max number of threads ecore will run
 * This returns the total number of threads that ecore will attempt to run
 * simultaneously.
 */
EAPI int
ecore_thread_max_get(void)
{
   return _ecore_thread_count_max;
}

/**
 * @brief Set the max number of threads that can run simultaneously
 * @param num The new maximum
 * This sets the maximum number of threads that ecore will try to run
 * simultaneously.  This number cannot be < 1 or >= 2x the number of active cpus.
 */
EAPI void
ecore_thread_max_set(int num)
{
   if (num < 1) return;
   /* avoid doing something hilarious by blocking dumb users */
   if (num >= (2 * eina_cpu_count())) return;

   _ecore_thread_count_max = num;
}

/**
 * @brief Reset the max number of threads that can run simultaneously
 * This resets the maximum number of threads that ecore will try to run
 * simultaneously to the number of active cpus.
 */
EAPI void
ecore_thread_max_reset(void)
{
   _ecore_thread_count_max = eina_cpu_count();
}

/**
 * @brief Get the number of threads which are available to be used
 * @return The number of available threads
 * This returns the number of threads slots that ecore has currently available.
 * Assuming that you haven't changed the max number of threads with @ref ecore_thread_max_set
 * this should be equal to (num_cpus - (active_running + active_feedback_running))
 */
EAPI int
ecore_thread_available_get(void)
{
   int ret;
#ifdef EFL_HAVE_THREADS
   LKL(_ecore_pending_job_threads_mutex);
   ret = _ecore_thread_count_max - _ecore_thread_count;
   LKU(_ecore_pending_job_threads_mutex);
   return ret;
#else
   return 0;
#endif
}

/**
 * @brief Add data to the thread for subsequent use
 * @param thread The thread context to add to
 * @param key The name string to add the data with
 * @param value The data to add
 * @param cb The callback to free the data with
 * @param direct If true, this will not copy the key string (like eina_hash_direct_add)
 * @return EINA_TRUE on success, EINA_FALSE on failure
 * This adds data to the thread context, allowing the thread
 * to retrieve and use it without complicated mutexing.  This function can only be called by a
 * *_run thread INSIDE the thread and will return EINA_FALSE in any case but success.
 * All data added to the thread will be freed with its associated callback (if present)
 * upon thread termination.  If no callback is specified, it is expected that the user will free the
 * data, but this is most likely not what you want.
 */
EAPI Eina_Bool
ecore_thread_local_data_add(Ecore_Thread *thread, const char *key, void *value, Eina_Free_Cb cb, Eina_Bool direct)
{
   Ecore_Pthread_Worker *worker = (Ecore_Pthread_Worker *) thread;
   Ecore_Thread_Data *d;
   Eina_Bool ret;

   if ((!thread) || (!key) || (!value))
     return EINA_FALSE;
#ifdef EFL_HAVE_THREADS
   if (!PHE(worker->self, PHS())) return EINA_FALSE;

   if (!worker->hash)
     worker->hash = eina_hash_string_small_new(_ecore_thread_data_free);

   if (!worker->hash)
     return EINA_FALSE;

   if (!(d = malloc(sizeof(Ecore_Thread_Data))))
     return EINA_FALSE;

   d->data = value;
   d->cb = cb;

   if (direct)
     ret = eina_hash_direct_add(worker->hash, key, d);
   else
     ret = eina_hash_add(worker->hash, key, d);
   CDB(worker->cond);
   return ret;
#else
   return EINA_TRUE;
#endif
}

/**
 * @brief Modify data in the thread, or add if not found
 * @param thread The thread context
 * @param key The name string to add the data with
 * @param value The data to add
 * @param cb The callback to free the data with
 * @return The old data associated with @p key on success if modified, NULL if added
 * This adds/modifies data in the thread context, adding only if modify fails.
 * This function can only be called by a *_run thread INSIDE the thread.
 * All data added to the thread pool will be freed with its associated callback (if present)
 * upon thread termination.  If no callback is specified, it is expected that the user will free the
 * data, but this is most likely not what you want.
 */
EAPI void *
ecore_thread_local_data_set(Ecore_Thread *thread, const char *key, void *value, Eina_Free_Cb cb)
{
   Ecore_Pthread_Worker *worker = (Ecore_Pthread_Worker *) thread;
   Ecore_Thread_Data *d, *r;
   void *ret;
   if ((!thread) || (!key) || (!value))
     return NULL;
#ifdef EFL_HAVE_THREADS
   if (!PHE(worker->self, PHS())) return NULL;

   if (!worker->hash)
     worker->hash = eina_hash_string_small_new(_ecore_thread_data_free);

   if (!worker->hash)
     return NULL;

   if (!(d = malloc(sizeof(Ecore_Thread_Data))))
     return NULL;

   d->data = value;
   d->cb = cb;

   r = eina_hash_set(worker->hash, key, d);
   CDB(worker->cond);
   ret = r->data;
   free(r);
   return ret;
#else
   return NULL;
#endif
}

/**
 * @brief Find data in the thread's data
 * @param thread The thread context
 * @param key The name string the data is associated with
 * @return The value, or NULL on error
 * This finds data in the thread context that has been previously added with @ref ecore_thread_local_data_add
 * This function can only be called by a *_run thread INSIDE the thread, and will return NULL
 * in any case but success.
 */

EAPI void *
ecore_thread_local_data_find(Ecore_Thread *thread, const char *key)
{
   Ecore_Pthread_Worker *worker = (Ecore_Pthread_Worker *) thread;
   Ecore_Thread_Data *d;

   if ((!thread) || (!key))
     return NULL;
#ifdef EFL_HAVE_THREADS
   if (!PHE(worker->self, PHS())) return NULL;

   if (!worker->hash)
     return NULL;

   d = eina_hash_find(worker->hash, key);
   return d->data;
#else
   return NULL;
#endif
}

/**
 * @brief Delete data from the thread's data
 * @param thread The thread context
 * @param key The name string the data is associated with
 * @return EINA_TRUE on success, EINA_FALSE on failure
 * This deletes the data pointer from the thread context which was previously added with @ref ecore_thread_local_data_add
 * This function can only be called by a *_run thread INSIDE the thread, and will return EINA_FALSE
 * in any case but success.  Note that this WILL free the data if a callback was specified.
 */
EAPI Eina_Bool
ecore_thread_local_data_del(Ecore_Thread *thread, const char *key)
{
   Ecore_Pthread_Worker *worker = (Ecore_Pthread_Worker *) thread;
   Ecore_Thread_Data *d;
   if ((!thread) || (!key))
     return EINA_FALSE;
#ifdef EFL_HAVE_THREADS
   if (!PHE(worker->self, PHS())) return EINA_FALSE;

   if (!worker->hash)
     return EINA_FALSE;
   if ((d = eina_hash_find(worker->hash, key)))
     _ecore_thread_data_free(d);
   return eina_hash_del_by_key(worker->hash, key);
#else
   return EINA_TRUE;
#endif
}

/**
 * @brief Add data to the global data
 * @param key The name string to add the data with
 * @param value The data to add
 * @param cb The optional callback to free the data with once ecore is shut down
 * @param direct If true, this will not copy the key string (like eina_hash_direct_add)
 * @return EINA_TRUE on success, EINA_FALSE on failure
 * This adds data to the global thread data, and will return EINA_FALSE in any case but success.
 * All data added to global can be manually freed, or a callback can be provided with @p cb which will
 * be called upon ecore_thread shutting down.  Note that if you have manually freed data that a callback
 * was specified for, you will most likely encounter a segv later on.
 */
EAPI Eina_Bool
ecore_thread_global_data_add(const char *key, void *value, Eina_Free_Cb cb, Eina_Bool direct)
{
   Eina_Bool ret;
   Ecore_Thread_Data *d;

   if ((!key) || (!value))
     return EINA_FALSE;
#ifdef EFL_HAVE_THREADS
   LRWKWL(_ecore_thread_global_hash_lock);
   if (!_ecore_thread_global_hash)
     _ecore_thread_global_hash = eina_hash_string_small_new(_ecore_thread_data_free);
   LRWKU(_ecore_thread_global_hash_lock);

   if (!(d = malloc(sizeof(Ecore_Thread_Data))))
     return EINA_FALSE;

   d->data = value;
   d->cb = cb;

   if (!_ecore_thread_global_hash)
     return EINA_FALSE;
   LRWKWL(_ecore_thread_global_hash_lock);
   if (direct)
     ret = eina_hash_direct_add(_ecore_thread_global_hash, key, d);
   else
     ret = eina_hash_add(_ecore_thread_global_hash, key, d);
   LRWKU(_ecore_thread_global_hash_lock);
   CDB(_ecore_thread_global_hash_cond);
   return ret;
#else
   return EINA_TRUE;
#endif
}

/**
 * @brief Add data to the global data
 * @param key The name string to add the data with
 * @param value The data to add
 * @param cb The optional callback to free the data with once ecore is shut down
 * @return An Ecore_Thread_Data on success, NULL on failure
 * This adds data to the global thread data and returns NULL, or replaces the previous data
 * associated with @p key and returning the previous data if it existed.  To see if an error occurred,
 * one must use eina_error_get.
 * All data added to global can be manually freed, or a callback can be provided with @p cb which will
 * be called upon ecore_thread shutting down.  Note that if you have manually freed data that a callback
 * was specified for, you will most likely encounter a segv later on.
 */
EAPI void *
ecore_thread_global_data_set(const char *key, void *value, Eina_Free_Cb cb)
{
   Ecore_Thread_Data *d, *r;
   void *ret;

   if ((!key) || (!value))
     return NULL;
#ifdef EFL_HAVE_THREADS
   LRWKWL(_ecore_thread_global_hash_lock);
   if (!_ecore_thread_global_hash)
     _ecore_thread_global_hash = eina_hash_string_small_new(_ecore_thread_data_free);
   LRWKU(_ecore_thread_global_hash_lock);

   if (!_ecore_thread_global_hash)
     return NULL;

   if (!(d = malloc(sizeof(Ecore_Thread_Data))))
     return NULL;

   d->data = value;
   d->cb = cb;

   LRWKWL(_ecore_thread_global_hash_lock);
   r = eina_hash_set(_ecore_thread_global_hash, key, d);
   LRWKU(_ecore_thread_global_hash_lock);
   CDB(_ecore_thread_global_hash_cond);

   ret = r->data;
   free(r);
   return ret;
#else
   return NULL;
#endif
}

/**
 * @brief Find data in the global data
 * @param key The name string the data is associated with
 * @return The value, or NULL on error
 * This finds data in the global data that has been previously added with @ref ecore_thread_global_data_add
 * This function will return NULL in any case but success.
 * All data added to global can be manually freed, or a callback can be provided with @p cb which will
 * be called upon ecore_thread shutting down.  Note that if you have manually freed data that a callback
 * was specified for, you will most likely encounter a segv later on.
 * @note Keep in mind that the data returned can be used by multiple threads at a time, so you will most likely want to mutex
 * if you will be doing anything with it.
 */

EAPI void *
ecore_thread_global_data_find(const char *key)
{
   Ecore_Thread_Data *ret;
   if (!key)
     return NULL;
#ifdef EFL_HAVE_THREADS
   if (!_ecore_thread_global_hash) return NULL;

   LRWKRL(_ecore_thread_global_hash_lock);
   ret = eina_hash_find(_ecore_thread_global_hash, key);
   LRWKU(_ecore_thread_global_hash_lock);
   return ret->data;
#else
   return NULL;
#endif
}

/**
 * @brief Delete data from the global data
 * @param key The name string the data is associated with
 * @return EINA_TRUE on success, EINA_FALSE on failure
 * This deletes the data pointer from the global data which was previously added with @ref ecore_thread_global_data_add
 * This function will return EINA_FALSE in any case but success.
 * Note that this WILL free the data if an @c Eina_Free_Cb was specified when the data was added.
 */
EAPI Eina_Bool
ecore_thread_global_data_del(const char *key)
{
   Eina_Bool ret;
   Ecore_Thread_Data *d;

   if (!key)
     return EINA_FALSE;
#ifdef EFL_HAVE_THREADS
   if (!_ecore_thread_global_hash)
     return EINA_FALSE;

   LRWKWL(_ecore_thread_global_hash_lock);
   if ((d = eina_hash_find(_ecore_thread_global_hash, key)))
     _ecore_thread_data_free(d);
   ret = eina_hash_del_by_key(_ecore_thread_global_hash, key);
   LRWKU(_ecore_thread_global_hash_lock);
   return ret;
#else
   return EINA_TRUE;
#endif
}

/**
 * @brief Find data in the global data and optionally wait for the data if not found
 * @param key The name string the data is associated with
 * @param seconds The amount of time in seconds to wait for the data.  If 0, the call will be async and not wait for data.
 * If < 0 the call will wait indefinitely for the data.
 * @return The value, or NULL on failure
 * This finds data in the global data that has been previously added with @ref ecore_thread_global_data_add
 * This function will return NULL in any case but success.
 * Use @p seconds to specify the amount of time to wait.  Use > 0 for an actual wait time, 0 to not wait, and < 0 to wait indefinitely.
 * @note Keep in mind that the data returned can be used by multiple threads at a time, so you will most likely want to mutex
 * if you will be doing anything with it.
 */
EAPI void *
ecore_thread_global_data_wait(const char *key, double seconds)
{
   double time = 0;
   Ecore_Thread_Data *ret = NULL;
   if (!key)
     return NULL;
#ifdef EFL_HAVE_THREADS
   if (!_ecore_thread_global_hash)
     return NULL;
   if (seconds > 0)
     time = ecore_time_get() + seconds;

   while (1)
     {
#ifndef _WIN32
        struct timespec t = { 0, 0 };

        t.tv_sec = (long int)time;
        t.tv_nsec = (long int)((time - (double)t.tv_sec) * 1000000000);
#else
        struct timeval t = { 0, 0 };

        t.tv_sec = (long int)time;
        t.tv_usec = (long int)((time - (double)t.tv_sec) * 1000000);
#endif
        LRWKRL(_ecore_thread_global_hash_lock);
        ret = eina_hash_find(_ecore_thread_global_hash, key);
        LRWKU(_ecore_thread_global_hash_lock);
        if ((ret) || (!seconds) || ((seconds > 0) && (time <= ecore_time_get())))
          break;
        LKL(_ecore_thread_global_hash_mutex);
        CDW(_ecore_thread_global_hash_cond, _ecore_thread_global_hash_mutex, &t);
        LKU(_ecore_thread_global_hash_mutex);
     }
   if (ret) return ret->data;
   return NULL;
#else
   return NULL;
#endif
}

/**
 * @}
 */

/**
 * @}
 */