diff --git a/include/object.h b/include/object.h index 8f4f9dc36a7a53452eece9cc4280f5c9eaf0e094..6ad8cea035c5a7b0c7215f51cee6301e9a800567 100644 --- a/include/object.h +++ b/include/object.h @@ -33,6 +33,7 @@ 202105140816:rxh 根据git的要求增加License 202107081052:rxh 修改object.h支持用c++实现LCOM对象 202107101536: rxh 修改INTERFACE_HEADER中__thisoffset的描述,避免出现从指针到int的截断警告 + 202108070740: rxh 修改AddRef和Release的实现,采用原子操作,支持多线程。 */ @@ -416,6 +417,22 @@ static int _obj##QueryInterface(HOBJECT object, IIDTYPE iid, const void **pInter return EIID_UNSUPPORTEDINTERFACE; \ } +#ifdef WIN32 +#include "windows.h" +#define INCREMENT(p) InterlockedIncrement(&p) +#define DECREMENT(p) InterlockedDecrement(&p) +#endif + +#ifdef __GNUC__ +#define INCREMENT(p) __sync_fetch_and_add(&p, 1); +#define DECREMENT(p) __sync_fetch_and_sub(&p, 1); +#endif + +#ifndef INCREMENT +#define INCREMENT(p) p++ +#define DECREMENT(p) p-- +#endif + #define OBJECT_RETURN_GEN(_obj, _objptr, _retvar, _sid) \ do \ { \ @@ -429,10 +446,10 @@ do \ static int _obj##AddRef(HOBJECT object) \ { \ _localstruct * pD; \ - if (!objectIsValid(object)) \ + if (!objectIsValid(object)) \ return EIID_INVALIDOBJECT; \ - pD = (_localstruct *)objectThis(object); \ - pD->__object_refcount++; \ + pD = (_localstruct *)objectThis(object); \ + INCREMENT(pD->__object_refcount); \ return pD->__object_refcount; \ } \ \ @@ -440,10 +457,10 @@ static int _obj##Release(HOBJECT object) \ { \ _localstruct * pD; \ int ret; \ - if (!objectIsValid(object)) \ + if (!objectIsValid(object)) \ return EIID_INVALIDOBJECT; \ - pD = (_localstruct *)objectThis(object); \ - pD->__object_refcount--; \ + pD = (_localstruct *)objectThis(object); \ + DECREMENT(pD->__object_refcount); \ ret = pD->__object_refcount; \ if (pD->__object_refcount <= 0) { \ pD->__object_refcount = 1; /* 为了保证在Destroy过程中不出现递归调用,这里将引用记数设置为1 */ \