VCOS_STATUS_T vcos_pthreads_timer_create(VCOS_TIMER_T *timer,
                                const char *name,
                                void (*expiration_routine)(void *context),
                                void *context)
{
   pthread_mutexattr_t lock_attr;
   VCOS_STATUS_T result = VCOS_SUCCESS;
   int settings_changed_initialized = 0;
   int lock_attr_initialized = 0;
   int lock_initialized = 0;

   (void)name;

   vcos_assert(timer);
   vcos_assert(expiration_routine);

   memset(timer, 0, sizeof(VCOS_TIMER_T));

   timer->orig_expiration_routine = expiration_routine;
   timer->orig_context = context;

   /* Create conditional variable for notifying the timer's thread
    * when settings change.
    */
   if (result == VCOS_SUCCESS)
   {
      int rc = pthread_cond_init(&timer->settings_changed, NULL);
      if (rc == 0)
         settings_changed_initialized = 1;
      else
         result = vcos_pthreads_map_error(rc);
   }

   /* Create attributes for the lock (we want it to be recursive) */
   if (result == VCOS_SUCCESS)
   {
      int rc = pthread_mutexattr_init(&lock_attr);
      if (rc == 0)
      {
         pthread_mutexattr_settype(&lock_attr, PTHREAD_MUTEX_RECURSIVE);
         lock_attr_initialized = 1;
      }
      else
      {
         result = vcos_pthreads_map_error(rc);
      }
   }

   /* Create lock for the timer structure */
   if (result == VCOS_SUCCESS)
   {
      int rc = pthread_mutex_init(&timer->lock, &lock_attr);
      if (rc == 0)
         lock_initialized = 1;
      else
         result = vcos_pthreads_map_error(rc);
   }

   /* Lock attributes are no longer needed */
   if (lock_attr_initialized)
      pthread_mutexattr_destroy(&lock_attr);

   /* Create the underlying thread */
   if (result == VCOS_SUCCESS)
   {
      int rc = pthread_create(&timer->thread, NULL, _timer_thread, timer);
      if (rc != 0)
         result = vcos_pthreads_map_error(rc);
   }

   /* Clean up if anything went wrong */
   if (result != VCOS_SUCCESS)
   {
      if (lock_initialized)
         pthread_mutex_destroy(&timer->lock);

      if (settings_changed_initialized)
         pthread_cond_destroy(&timer->settings_changed);
   }

   return result;
}
/*!-----------------------------------------------------------------------

    s m _ i n i t i a l i z e

    @brief Initialize the data structures in a new shared memory segment.

    The specified file (referenced by the supplied file descriptor) will be
    mapped into virtual memory and the size of the file adjusted to match the
    desired size of the shared memory segment.

    This function will set up all of the data structures in the shared memory
    segment for use.  This function should be called after a brand new shared
    memory segment has been created and opened on disk.  This function should
    not be called on an existing shared memory segment that contains data as
    all of that data will be deleted by this function.

    @param[in] fd - The file descriptor of the file associated with this
               shared memory segment.

    @param[in] sharedMemorySegmentSize - The size of the shared memory
               segment in bytes.

    @return The new memory address of where the shared memory segment begins.
            On error, a null pointer is returned and errno will be set to
            indicate the error that was encountered.

------------------------------------------------------------------------*/
sharedMemory_t* sm_initialize ( int fd, size_t sharedMemorySegmentSize )
{
    int             status;
    sharedMemory_t* sharedMemory;

    LOG ( "Initializing user shared memory - fd[%d], Size[%'lu]\n", fd,
          sharedMemorySegmentSize );
    //
    //  Map the shared memory file into virtual memory.
    //
    sharedMemory = mmap ( NULL, INITIAL_SHARED_MEMORY_SIZE,
                          PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0 );
    if ( sharedMemory == MAP_FAILED )
    {
        printf ( "Unable to map the user shared memory segment. errno: %u[%m].\n",
                 errno );
        return 0;
    }
    //
    //  Make the pseudo-file for the shared memory segment the size of the
    //  shared memory segment.  Note that this will destroy any existing data
    //  if the segment already exists.
    //
    status = ftruncate ( fd, INITIAL_SHARED_MEMORY_SIZE );
    if (status != 0)
    {
        printf ( "Unable to resize the user shared memory segment to [%'lu] bytes - "
                 "errno: %u[%m].\n", INITIAL_SHARED_MEMORY_SIZE, errno );
        return 0;
    }
    //
    //  Set all of the data in this shared memory segment to zero.
    //
    // TODO: (void)memset ( sharedMemory, 0, sharedMemorySegmentSize );
    (void)memset ( sharedMemory, 0xaa, sharedMemorySegmentSize );

    //
    //  Initialize our global pointer to the shared memory segment.
    //
    smControl = sharedMemory;

    //
    //  Initialize the fields in the shared memory control structure.  This
    //  structure is located at the beginning of the shared memory region that
    //  we just created and the fields here are adjusted to take into account
    //  the size of the user shared memory structure.
    //
    smControl->sharedMemorySegmentSize = sharedMemorySegmentSize;
    smControl->currentOffset           = smSize;
    smControl->currentSize             = sharedMemorySegmentSize - smSize;
    smControl->systemInitialized       = 0;

    //
    //  Create the mutex attribute initializer that we can use to initialize
    //  all of the mutexes in the B-trees.
    //
    pthread_mutexattr_t* mutexAttributes = &smControl->masterMutexAttributes;

    status =  pthread_mutexattr_init ( mutexAttributes );
    if ( status != 0 )
    {
        printf ( "Unable to initialize mutex attributes - errno: %u[%m].\n",
                 status );
        return 0;
    }
    //
    // Set this mutex to be a process shared mutex.
    //
    status = pthread_mutexattr_setpshared ( mutexAttributes,
                                            PTHREAD_PROCESS_SHARED );
    if ( status != 0 )
    {
        printf ( "Unable to set shared mutex attribute - errno: %u[%m].\n",
                 status );
        return 0;
    }
    //
    // Set this mutex to be a recursive mutex.
    //
    status = pthread_mutexattr_settype ( mutexAttributes,
                                         PTHREAD_MUTEX_RECURSIVE );
    if ( status != 0 )
    {
        printf ( "Unable to set recursive mutex attribute - errno: %u[%m].\n",
                 status );
        return 0;
    }
    //
    //  Create the condition variable initializer that we can use to
    //  initialize all of the condition variables in the shared memory
    //  segment.
    //
    pthread_condattr_t* conditionVariableAttributes =
        &smControl->masterCvAttributes;

    status = pthread_condattr_init ( conditionVariableAttributes );

    if ( status != 0 )
    {
        printf ( "Unable to initialize condition variable attributes - "
                 "errno: %u[%m].\n", status );
        return 0;
    }
    //
    //  Set this condition variable to be shared between processes.
    //
    status = pthread_condattr_setpshared ( conditionVariableAttributes,
                                           PTHREAD_PROCESS_SHARED );
    if ( status != 0 )
    {
        printf ( "Unable to set shared condition variable attributes - "
                 "errno: %u[%m].\n", status );
        return 0;
    }
    //
    //  Initialize the shared memory mutex.
    //
    status = pthread_mutex_init ( &smControl->smLock, mutexAttributes );
    if ( status != 0 )
    {
        printf ( "Unable to initialize shared memory manager mutex - errno: "
                 "%u[%m].\n", status );
        return 0;
    }
    //
    //  Now put the rest of the preallocated memory into the free memory pool.
    //
    //  Define the memory chunk data structure at the beginning of the free
    //  section of memory and initialize it.
    //
    memoryChunk_t* availableMemory = toAddress ( smControl->currentOffset );

    availableMemory->marker      = SM_FREE_MARKER;
    availableMemory->segmentSize = smControl->currentSize;
    availableMemory->offset      = smControl->currentOffset;
    availableMemory->type        = TYPE_USER;

    //
    //  Go insert this memory into the shared memory allocation B-trees.
    //
    (void)insertMemoryChunk ( availableMemory );

    //
    //  Set the "initialized" flag to indicate that the shared memory
    //  allocation system is in a usable state.  Note that this indicator is
    //  primarily used by the sm_malloc function to determine how to allocate
    //  memory for the shared memory memory management function B-trees that
    //  we just defined above.
    //
    smControl->systemInitialized = 1;

    //
    //  Let the user know that the system initialization has been completed.
    //
    LOG ( "\n===== User shared memory is Initialized at %p =====\n\n",
          smControl );

#ifdef VSI_DEBUG
    dumpSM();
#endif

    //
    //  Return the address of the shared memory segment to the caller.
    //
    return smControl;
}
Example #3
0
File: Log.cpp Project: crowm/SATPI
void open_app_log() {
	pthread_mutexattr_t attr;
	pthread_mutexattr_init(&attr);
	pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
	pthread_mutex_init(&mutex, &attr);
}
Example #4
0
local void arenaAction(Arena *arena, int action)
{
	TurfStats *ts, **p_ts = P_ARENA_DATA(arena, tskey);

	if (action == AA_PRECREATE)
	{
		pthread_mutexattr_t attr;

		pthread_mutexattr_init(&attr);
		pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
		pthread_mutex_init((pthread_mutex_t*)P_ARENA_DATA(arena, mtxkey), &attr);
		pthread_mutexattr_destroy(&attr);
	}
	else if (action == AA_PRECREATE)
	{
		ts = amalloc(sizeof(TurfStats));
		*p_ts = ts;
	}

	ts = *p_ts;
	LOCK_STATUS(arena);

	if (action == AA_CREATE)
	{
		ConfigHandle c = arena->cfg;
		ts->maxHistory = config->GetInt(c, "TurfStats", "MaxHistory", 0);
		if (ts->maxHistory<0)
			ts->maxHistory = 0;
		ts->statsOnDing = config->GetInt(c, "TurfStats", "StatsOnDing", 1);
		if (ts->statsOnDing<1)
			ts->statsOnDing=1;

		ts->dingCount = 0;
		ts->numStats = 0;
		LLInit(&ts->stats); /* initalize list of stats */
	}
	else if (action == AA_DESTROY)
	{
		/* free history array */
		clearHistory(arena);

		/* might as well, just in case to be safe */
		ts->numStats = 0;
		ts->dingCount = 0;
	}
	else if (action == AA_CONFCHANGED)
	{
		int newMaxHistory;
		ConfigHandle c = arena->cfg;

		ts->statsOnDing = config->GetInt(c, "TurfStats", "StatsOnDing", 1);
		if (ts->statsOnDing<1)
			ts->statsOnDing=1;

		newMaxHistory = config->GetInt(c, "TurfStats", "MaxHistory", 0);
		if (newMaxHistory < 0)
			newMaxHistory = 0;  /* max history must be >= 0 */
		if (newMaxHistory != ts->maxHistory)
		{
			ts->maxHistory = newMaxHistory;

			/* erase history */
			clearHistory(arena);
		}
	}

	UNLOCK_STATUS(arena);

	if (action == AA_DESTROY)
	{
		afree(ts);
	}
	else if (action == AA_POSTDESTROY)
	{
		pthread_mutex_destroy((pthread_mutex_t*)P_ARENA_DATA(arena, mtxkey));
	}
}
Example #5
0
int main (int argc, char *argv[])
{

#ifdef PTHREADS
  int ret;
  pthread_attr_t  attr;
  pthread_t       tid1, tid2, tid3;
  pthread_mutexattr_t Attr;
  pthread_mutexattr_init(&Attr);
  pthread_mutexattr_settype(&Attr, PTHREAD_MUTEX_ERRORCHECK);
  if (pthread_mutex_init(&mutexsum, &Attr)) {
    printf("Error while using pthread_mutex_init\n");
  }
#endif /* PTHREADS */

#ifdef TAU_MPI
  int rc = MPI_SUCCESS;
#if defined(PTHREADS)
  rc = MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided);
  printf("MPI_Init_thread: provided = %d, MPI_THREAD_MULTIPLE=%d\n", provided, MPI_THREAD_MULTIPLE);
#elif defined(TAU_OPENMP)
  rc = MPI_Init_thread(&argc, &argv, MPI_THREAD_FUNNELED, &provided);
  printf("MPI_Init_thread: provided = %d, MPI_THREAD_FUNNELED=%d\n", provided, MPI_THREAD_FUNNELED);
#else
  rc = MPI_Init(&argc, &argv);
#endif /* THREADS */
  if (rc != MPI_SUCCESS) {
    char *errorstring;
    int length = 0;
    MPI_Error_string(rc, errorstring, &length);
    printf("Error: MPI_Init failed, rc = %d\n%s\n", rc, errorstring);
    exit(1);
  }
#endif /* TAU_MPI */

#ifdef PTHREADS
  if (ret = pthread_create(&tid1, NULL, threaded_func, NULL) )
  {
    printf("Error: pthread_create (1) fails ret = %d\n", ret);
    exit(1);
  }

  if (ret = pthread_create(&tid2, NULL, threaded_func, NULL) )
  {
    printf("Error: pthread_create (2) fails ret = %d\n", ret);
    exit(1);
  }

  if (ret = pthread_create(&tid3, NULL, threaded_func, NULL) )
  {
    printf("Error: pthread_create (3) fails ret = %d\n", ret);
    exit(1);
  }

#endif /* PTHREADS */

  /* On thread 0: */
  int i;
  //for (i = 0 ; i < 100 ; i++) {
  do_work();
  //}

#ifdef PTHREADS
  if (ret = pthread_join(tid1, NULL) )
  {
    printf("Error: pthread_join (1) fails ret = %d\n", ret);
    exit(1);
  }

  if (ret = pthread_join(tid2, NULL) )
  {
    printf("Error: pthread_join (2) fails ret = %d\n", ret);
    exit(1);
  }

  if (ret = pthread_join(tid3, NULL) )
  {
    printf("Error: pthread_join (3) fails ret = %d\n", ret);
    exit(1);
  }

  pthread_mutex_destroy(&mutexsum);
#endif /* PTHREADS */

#ifdef TAU_MPI
  MPI_Finalize();
#endif /* TAU_MPI */
  printf ("Done.\n");

  return 0;
}
Example #6
0
GroupManager::GroupManager(NdnMediaProcess *pNdnMediaPro) {

	ruMutex = new QMutex(QMutex::Recursive);
	pthread_mutexattr_init(&attr);
	pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
	pthread_mutex_init(&gm_mutex, &attr);
    pGroupManager = this;

    this->pNdnMediaPro = pNdnMediaPro;

	QDomDocument settings;
	QString configFileName = QDir::homePath() + "/" + \
							".actd" + "/" + ".config";
	QFile config(configFileName);
	if (!config.exists()) 
		critical("Config file does not exist!");
	
	if (!config.open(QIODevice::ReadOnly))
		critical("Can not open config file!");
	
	if (!settings.setContent(&config)) {
		config.close();
		critical("can not parse config file!");
	}
	config.close();
	
	QDomElement docElem = settings.documentElement(); //<config>
	QDomNode n = docElem.firstChild();

	isPrivate = false;
	QString qsConfKey;
	QString qsSessionKey;
	QByteArray qbaSK;
	while(!n.isNull()) {
		if (n.nodeName() == "prefix") {
			prefix = n.toElement().text();
		} else if (n.nodeName() == "confName") {
			confName = n.toElement().text();
		} else if (n.nodeName() == "channelName") {
		} else if (n.nodeName() == "private") {
			QString p = n.toElement().text();
			if (p == "true")
				isPrivate = true;
			else
				isPrivate = false;
		} else if (n.nodeName() == "confKey" && isPrivate) {
			qsConfKey = n.toElement().text();
			QByteArray qbaCK = \
				QByteArray::fromBase64(qsConfKey.toLocal8Bit()); 
			memcpy(conferenceKey, qbaCK.data(), qbaCK.size());
		} else if (n.nodeName() == "sessionKey" && isPrivate) {
			qsSessionKey = n.toElement().text();
			qbaSK = \
				QByteArray::fromBase64(qsSessionKey.toLocal8Bit());

		} else {
			debug("unknown atrribute in config file!");
		}
		n = n.nextSibling();

	}

	if (confName.isEmpty())
		critical("no confName in config!");
	
	if (isPrivate && (qsConfKey.isEmpty() || qsSessionKey.isEmpty()))
		isPrivate = false;
	
	if (isPrivate) {
		pNdnMediaPro->setPrivate();
		pNdnMediaPro->setSK(qbaSK);
	}

	ndnContext();
	
    localUser = NULL;

    // ui_session id for remoteUsers
	// 5000 at maximum
    for (int i = 5001; i < 10000; ++i)
        qqRSesIds.enqueue(i);

}
#include "OperateDiskProc.h"
#include "transfers_base.h"
#include "netManager.h"

#include "LOGCTRL.h"
//#define NO_POS_DEBUG
#include "pos_debug.h"

static	INT8 tmpBuff[MAX_SEND_BUF_LEN];


#if SKJ_PTHREAD_KPMUTEX_OPEN == 1
pthread_mutex_t *g_skjkpmutex = new pthread_mutex_t;
pthread_mutexattr_t skjmattr;
int skjret = pthread_mutexattr_init(&skjmattr);
int skjret1 = pthread_mutexattr_settype(&skjmattr, PTHREAD_MUTEX_RECURSIVE_NP);
int skjret2 = pthread_mutex_init(g_skjkpmutex, &skjmattr);
int skjret3 = pthread_mutexattr_destroy(&skjmattr);
//static pthread_mutex_t	g_skjkpmutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
#endif


CYWXmlBase::CYWXmlBase(CYWXML_GY &ywxml_gy):m_ywxml_gy(ywxml_gy)
{
	m_ywlx = ywxml_gy.m_strID;
	m_servip = "";
	m_servport = "";
	m_servpath = "";
	m_pin = "";
	m_Err = "";
	m_nsrsbh = "";
 mutex(int type = PTHREAD_MUTEX_DEFAULT) {
   pthread_mutexattr_t attr;
   pthread_mutexattr_init(&attr);
   pthread_mutexattr_settype(&attr, type);
   pthread_mutex_init(&_mutex, &attr);
 }
Example #9
0
File: 4-3.c Project: 1587/ltp
/* Test function -- This one calls pthread_mutex_trylock and check that no EINTR is returned. */
void *test(void *arg)
{
	int ret = 0;
	int i;
	long pshared;
	pthread_mutex_t mtx[NSCENAR + 2];
	pthread_mutexattr_t ma[NSCENAR + 1];

	/* We don't block the signals SIGUSR1 and SIGUSR2 for this THREAD */
	ret = pthread_sigmask(SIG_UNBLOCK, &usersigs, NULL);
	if (ret != 0) {
		UNRESOLVED(ret,
			   "Unable to unblock SIGUSR1 and SIGUSR2 in worker thread");
	}

	/* System abilities */
	pshared = sysconf(_SC_THREAD_PROCESS_SHARED);

	/* Initialize the mutex objects according to the scenarii */
	for (i = 0; i < NSCENAR; i++) {
		ret = pthread_mutexattr_init(&ma[i]);
		if (ret != 0) {
			UNRESOLVED(ret,
				   "[parent] Unable to initialize the mutex attribute object");
		}
#ifndef WITHOUT_XOPEN
		/* Set the mutex type */
		ret = pthread_mutexattr_settype(&ma[i], scenarii[i].m_type);
		if (ret != 0) {
			UNRESOLVED(ret, "[parent] Unable to set mutex type");
		}
#endif
		/* Set the pshared attributes, if supported */
		if ((pshared > 0) && (scenarii[i].m_pshared != 0)) {
			ret =
			    pthread_mutexattr_setpshared(&ma[i],
							 PTHREAD_PROCESS_SHARED);
			if (ret != 0) {
				UNRESOLVED(ret,
					   "[parent] Unable to set the mutex process-shared");
			}
		}

		/* Initialize the mutex */
		ret = pthread_mutex_init(&mtx[i], &ma[i]);
		if (ret != 0) {
			UNRESOLVED(ret, "[parent] Mutex init failed");
		}

	}
	/* Default mutexattr object */
	ret = pthread_mutexattr_init(&ma[i]);
	if (ret != 0) {
		UNRESOLVED(ret,
			   "[parent] Unable to initialize the mutex attribute object");
	}
	ret = pthread_mutex_init(&mtx[i], &ma[i]);
	if (ret != 0) {
		UNRESOLVED(ret, "[parent] Mutex init failed");
	}
	/* Default mutex */
	ret = pthread_mutex_init(&mtx[i + 1], NULL);
	if (ret != 0) {
		UNRESOLVED(ret, "[parent] Mutex init failed");
	}

	/* do the real testing */
	while (do_it) {
		count_ope++;

		ret = pthread_mutex_trylock(&mtx[count_ope % (NSCENAR + 2)]);
		if (ret == EINTR) {
			FAILED("EINTR was returned");
		}
		if (ret != 0) {
			UNRESOLVED(ret, "1st trylock failed");
		}

		ret = pthread_mutex_trylock(&mtx[count_ope % (NSCENAR + 2)]);
		if (ret == EINTR) {
			FAILED("EINTR was returned");
		}
		if (ret == 0) {
			ret =
			    pthread_mutex_unlock(&mtx
						 [count_ope % (NSCENAR + 2)]);
			if (ret != 0) {
				UNRESOLVED(ret, "Unlocking the mutex failed");
			}
			ret = EBUSY;
		}
		if (ret != EBUSY) {
			UNRESOLVED(ret, "Unexpected error was returned.");
		}

		ret = pthread_mutex_unlock(&mtx[count_ope % (NSCENAR + 2)]);
		if (ret != 0) {
			UNRESOLVED(ret, "Failed to unlock the mutex");
		}
	}

	/* Destroy everything */
	for (i = 0; i <= NSCENAR; i++) {
		ret = pthread_mutex_destroy(&mtx[i]);
		if (ret != 0) {
			UNRESOLVED(ret, "Failed to destroy the mutex");
		}

		ret = pthread_mutexattr_destroy(&ma[i]);
		if (ret != 0) {
			UNRESOLVED(ret,
				   "Failed to destroy the mutex attr object");
		}
	}
	ret = pthread_mutex_destroy(&mtx[i]);
	if (ret != 0) {
		UNRESOLVED(ret, "Failed to destroy the mutex");
	}

	return NULL;
}
Example #10
0
void recursive_mutex_test(void)
{
  pthread_t thread[NTHREADS];
#ifdef SDCC
  pthread_addr_t result[NTHREADS];
  pthread_attr_t attr;
#endif
  pthread_mutexattr_t mattr;
  int type;
  int status;
  int i;

  /* Initialize the mutex attributes */

  pthread_mutexattr_init(&mattr);
  status = pthread_mutexattr_settype(&mattr, PTHREAD_MUTEX_RECURSIVE);
  if (status != 0)
    {
      printf("recursive_mutex_test: ERROR pthread_mutexattr_settype failed, status=%d\n", status);
    }

  status = pthread_mutexattr_gettype(&mattr, &type);
  if (status != 0)
    {
      printf("recursive_mutex_test: ERROR pthread_mutexattr_gettype failed, status=%d\n", status);
    }
  if (type != PTHREAD_MUTEX_RECURSIVE)
    {
      printf("recursive_mutex_test: ERROR pthread_mutexattr_gettype return type=%d\n", type);
    }

  /* Initialize the mutex */

  printf("recursive_mutex_test: Initializing mutex\n");
  status = pthread_mutex_init(&mut, &mattr);
  if (status != 0)
    {
      printf("recursive_mutex_test: ERROR pthread_mutex_init failed, status=%d\n", status);
    }

  /* Start the threads -- all at the same, default priority */

  for (i = 0; i < NTHREADS; i++)
    {
      printf("recursive_mutex_test: Starting thread %d\n", i+1);
#ifdef SDCC
      (void)pthread_attr_init(&attr);
      status = pthread_create(&thread[i], &attr, thread_outer, (pthread_addr_t)i+1);
#else
      status = pthread_create(&thread[i], NULL, thread_outer, (pthread_addr_t)i+1);
#endif
      if (status != 0)
        {
          printf("recursive_mutex_test: ERROR thread#%d creation: %d\n", i+1, status);
        }
    }

  /* Wait for all; of the threads to complete */

  for (i = 0; i < NTHREADS; i++)
    {
      printf("recursive_mutex_test: Waiting for thread %d\n", i+1);
#ifdef SDCC
      pthread_join(thread[i], &result[i]);
#else
      pthread_join(thread[i], NULL);
#endif
    }

  printf("recursive_mutex_test: Complete\n");
}
TInt CTestSemtrywait::TestSem392( )
	{
	
	int errsum=0, err = 0;
	int retval = 0;
	ThreadData lThreadData;

	sem_t lSignalSemaphore;
	sem_t lSuspendSemaphore;

	sem_t           lTestSemaphore;
	pthread_mutex_t lTestMutex;
	pthread_cond_t  lTestCondVar;
	pthread_condattr_t  lCondAttr;
	pthread_mutexattr_t lTestMutexAttr;

	pthread_mutexattr_t defaultattr;
	pthread_mutexattr_t errorcheckattr;
	pthread_mutexattr_t recursiveattr;

	pthread_mutexattr_init(&defaultattr);
	pthread_mutexattr_init(&errorcheckattr);
	pthread_mutexattr_init(&recursiveattr);

	pthread_mutexattr_settype(&errorcheckattr,PTHREAD_MUTEX_ERRORCHECK);
	pthread_mutexattr_settype(&recursiveattr,PTHREAD_MUTEX_RECURSIVE);


	pthread_mutex_t l_staticmutex = PTHREAD_MUTEX_INITIALIZER;
	pthread_mutex_t l_errorcheckmutex = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
	pthread_mutex_t l_recursivemutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
    pthread_cond_t  l_staticcondvar = PTHREAD_COND_INITIALIZER;


    CommonData lCommonData;
    lCommonData.iStaticMutex = &l_staticmutex;
	lCommonData.iErrorCheckMutex = &l_errorcheckmutex;
	lCommonData.iRecursiveMutex = &l_recursivemutex;
	lCommonData.iStaticCondVar = &l_staticcondvar;

	retval = sem_init(&lSignalSemaphore,0,0);
	if(retval != 0)
		{
		return retval;
		}

	retval = sem_init(&lSuspendSemaphore,0,0);
	if(retval != 0)
		{
		return retval;
		}

	lThreadData.iSignalSemaphore = &lSignalSemaphore;
	lThreadData.iSuspendSemaphore = &lSuspendSemaphore;
	lThreadData.iTestSemaphore   = &lTestSemaphore;
	lThreadData.iTestMutex       = &lTestMutex;
	lThreadData.iTestMutexAttr   = &lTestMutexAttr;
	lThreadData.iTestCondVar     = &lTestCondVar;
	lThreadData.iDefaultAttr     = &defaultattr;
	lThreadData.iErrorcheckAttr = &errorcheckattr;
	lThreadData.iRecursiveAttr   = &recursiveattr;

	lThreadData.iCondAttr        = &lCondAttr;
	for (int loop = 0; loop < EThreadMain; loop++)
		{
	    g_spinFlag[loop] = true;
		}
	lThreadData.iSuspending      = false;
	lThreadData.iSpinCounter     = 0;
	lThreadData.iCurrentCommand  = -1;
	lThreadData.iSelf            = EThreadMain;
	lThreadData.iValue           = 0;
	lThreadData.iRetValue        = 0;
	lThreadData.ierrno           = 0;
	lThreadData.iExpectederrno   = 0;
	lThreadData.iTimes           = 0;
	lThreadData.iStopped         = false;
	lThreadData.iCommonData      = &lCommonData;

	retval = SemInit(&lThreadData);
	
	fp=func2;
	retval = ThreadCreate(&lThreadData, (void*) EThread1);
	
	fp=func4;
	retval = ThreadCreate(&lThreadData, (void*) EThread2);

	retval = SemPost(&lThreadData);
	retval = ThreadDestroy(&lThreadData, (void*) EThread1);
	retval = ThreadDestroy(&lThreadData, (void*) EThread2);
	retval = SemDestroy(&lThreadData);
	StopThread(&lThreadData);
	
	err = pthread_cond_destroy(&l_staticcondvar);
	if(err != EINVAL)
		{
		errsum += err;
		}
    err = pthread_mutex_destroy(&l_recursivemutex);
	if(err != EINVAL)
		{
		errsum += err;
		}
    err = pthread_mutex_destroy(&l_errorcheckmutex);
	if(err != EINVAL)
		{
		errsum += err;
		}
    err = pthread_mutex_destroy(&l_staticmutex);
	if(err != EINVAL)
		{
		errsum += err;
		}
    err = pthread_mutexattr_destroy(&recursiveattr);
	if(err != EINVAL)
		{
		errsum += err;
		}
	err = pthread_mutexattr_destroy(&errorcheckattr);
	if(err != EINVAL)
		{
		errsum += err;
		}
	err = pthread_mutexattr_destroy(&defaultattr);
	if(err != EINVAL)
		{
		errsum += err;
		}
    err = sem_destroy(&lSignalSemaphore);
	if(err != EINVAL)
		{	
		errsum += err;
		}
	err = sem_destroy(&lSuspendSemaphore);
	if(err != EINVAL)
		{
		errsum += err;
		}

	return retval+errsum;
	
	}
Example #12
0
static STATUS __taskInit(struct wind_task *task,
			 struct WIND_TCB *tcb, const char *name,
			 int prio, int flags, FUNCPTR entry, int stacksize)
{
	struct threadobj_init_data idata;
	pthread_mutexattr_t mattr;
	struct sched_param param;
	pthread_attr_t thattr;
	int ret, cprio;

	ret = check_task_priority(prio, &cprio);
	if (ret) {
		errno = ret;
		return ERROR;
	}

	if (name == NULL || *name == '\0')
		sprintf(task->name, "t%lu", ++anon_tids);
	else {
		strncpy(task->name, name, sizeof(task->name));
		task->name[sizeof(task->name) - 1] = '\0';
	}

	__RT(pthread_mutexattr_init(&mattr));
	__RT(pthread_mutexattr_settype(&mattr, PTHREAD_MUTEX_RECURSIVE));
	__RT(pthread_mutexattr_setprotocol(&mattr, PTHREAD_PRIO_INHERIT));
	__RT(pthread_mutexattr_setpshared(&mattr, mutex_scope_attribute));
	__RT(pthread_mutex_init(&task->safelock, &mattr));
	__RT(pthread_mutexattr_destroy(&mattr));

	task->tcb = tcb;
	tcb->opaque = task;
	/*
	 * CAUTION: tcb->status in only modified by the owner task
	 * (see suspend/resume hooks), or when such task is guaranteed
	 * not to be running, e.g. in taskActivate(). So we do NOT
	 * take any lock specifically for updating it. However, we
	 * know that a memory barrier will be issued shortly after
	 * such updates because of other locking being in effect, so
	 * we don't explicitely have to provide for it.
	 */
	tcb->status = WIND_SUSPEND;
	tcb->safeCnt = 0;
	tcb->flags = flags;
	tcb->entry = entry;

	pthread_attr_init(&thattr);

	if (stacksize == 0)
		stacksize = PTHREAD_STACK_MIN * 4;
	else if (stacksize < PTHREAD_STACK_MIN)
		stacksize = PTHREAD_STACK_MIN;

	memset(&param, 0, sizeof(param));
	param.sched_priority = cprio;
	pthread_attr_setinheritsched(&thattr, PTHREAD_EXPLICIT_SCHED);
	pthread_attr_setschedpolicy(&thattr, SCHED_RT);
	pthread_attr_setschedparam(&thattr, &param);
	pthread_attr_setstacksize(&thattr, stacksize);
	pthread_attr_setscope(&thattr, thread_scope_attribute);
	pthread_attr_setdetachstate(&thattr, PTHREAD_CREATE_JOINABLE);

	idata.magic = task_magic;
	idata.wait_hook = task_wait_hook;
	idata.suspend_hook = task_suspend_hook;
	idata.finalizer = task_finalizer;
	idata.priority = cprio;
	threadobj_init(&task->thobj, &idata);

	ret = __bt(cluster_addobj(&wind_task_table, task->name, &task->cobj));
	if (ret) {
		warning("duplicate task name: %s", task->name);
		threadobj_destroy(&task->thobj);
		__RT(pthread_mutex_destroy(&task->safelock));
		errno = S_objLib_OBJ_ID_ERROR;
		return ERROR;
	}

	registry_init_file(&task->fsobj, &registry_ops);

	ret = __bt(-__RT(pthread_create(&task->thobj.tid, &thattr,
					&task_trampoline, task)));
	pthread_attr_destroy(&thattr);
	if (ret) {
		registry_destroy_file(&task->fsobj);
		cluster_delobj(&wind_task_table, &task->cobj);
		threadobj_destroy(&task->thobj);
		__RT(pthread_mutex_destroy(&task->safelock));
		errno = ret == -EAGAIN ? S_memLib_NOT_ENOUGH_MEMORY : -ret;
		return ERROR;
	}

	return OK;
}
Example #13
0
 void init() {
   pthread_mutexattr_t attr;
   pthread_mutexattr_init(&attr);
   pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
   assert(pthread_mutex_init(&native_, &attr) == 0);
 }
Example #14
0
int log_init()
{
	time_t t;
	struct tm tm;
	int result = 0;
	int log_thread_lock_init = 0, disk_thread_lock_init = 0, disk_thread_cond_init = 0;

	pthread_mutexattr_t mtxAttr;
	pthread_t disk_pthread_id;
	pthread_attr_t thread_attr;

	if (logger_init_flag) {
		fprintf(stderr, "logger module has already been init!!\n");
		return 1;
	}

	do {
		pContext = (LogContext *)malloc(sizeof(LogContext));

		if (pContext == NULL) {
			fprintf(stderr, "malloc %lu bytes fail, errno: %d, error info: %s", sizeof(LogContext), errno, STRERROR(errno));
			return (errno != 0) ? errno : ENOMEM;
		}

		log_level = LOG_INFO;

		pContext->log_fd = STDERR_FILENO;
		pContext->log_base_path = NULL;
		pContext->log_filename_prefix = NULL;
		pContext->log_to_cache = false;
		pContext->logrotate_cycle = ROTATE_CYCLE_DAY;

		/* 初始化日志buff */
		pContext->log_buff = (char *)malloc(LOG_BUFF_SIZE);

		if (pContext->log_buff == NULL) {
			fprintf(stderr, "malloc %d bytes fail, errno: %d, error info: %s", LOG_BUFF_SIZE, errno, STRERROR(errno));
			result = (errno != 0) ? errno : ENOMEM;
			break;
		}

		pContext->pcurrent_buff = pContext->log_buff;

		/* 设置锁为纠错锁, 同一线程不能重复加锁, 加上的锁只能由本线程解锁. 先等待锁的线程先获得锁 */
		pthread_mutexattr_init(&mtxAttr);
		pthread_mutexattr_settype(&mtxAttr, PTHREAD_MUTEX_ERRORCHECK_NP);

		if ((result = pthread_mutex_init(&(pContext->log_thread_lock), &mtxAttr)) != 0) {
			fprintf(stderr, "call pthread_mutex_init fail, errno: %d, error info: %s", result, STRERROR(result));
			break;
		}

		pthread_mutexattr_destroy(&mtxAttr);
		log_thread_lock_init = 1;

		/* 初始化写磁盘线程上下文 */
		if ((result = pthread_mutex_init(&(pContext->disk_thread_ctx.disk_thread_lock), NULL)) != 0) {
			fprintf(stderr, "call pthread_mutex_init fail, errno: %d, error info: %s", result, STRERROR(result));
			break;
		}

		disk_thread_lock_init = 1;

		if ((result = pthread_cond_init(&(pContext->disk_thread_ctx.disk_thread_cond), NULL)) != 0) {
			fprintf(stderr, "call pthread_cond_init fail, errno: %d, error info: %s", result, STRERROR(result));
			break;
		}

		disk_thread_cond_init = 1;

		pContext->disk_thread_ctx.disk_thread_stop = false;
		pContext->disk_thread_ctx.blocking_queue = new std::deque<std::string>;

		/* 启动磁盘线程 */
		pthread_attr_init(&thread_attr);
		pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);

		if ((result = pthread_create(&disk_pthread_id, &thread_attr, disk_write_thread, NULL)) != 0) {
			fprintf(stderr, "call pthread_create fail, errno: %d, error info: %s", result, STRERROR(result));
			break;
		}

		pContext->disk_thread_ctx.disk_pthread_id = disk_pthread_id;
		pthread_attr_destroy(&thread_attr);

		/* 等待磁盘线程运行成功 */
		pthread_mutex_init(&thread_init_lock, NULL);
		pthread_cond_init(&thread_init_cond, NULL);

		pthread_mutex_lock(&thread_init_lock);
		while (!thread_init_flag) {
			pthread_cond_wait(&thread_init_cond, &thread_init_lock);	
		}
		pthread_mutex_unlock(&thread_init_lock);

		/* 记录当前时间 */
		t = time(NULL);
		localtime_r(&t, &tm);

		switch (pContext->logrotate_cycle) {
		case ROTATE_CYCLE_NONE:
			last_log_time = -1;
			break;

		case ROTATE_CYCLE_MINUTE:
			last_log_time = tm.tm_min;
			break;

		case ROTATE_CYCLE_HOUR:
			last_log_time = tm.tm_hour;
			break;

		case ROTATE_CYCLE_DAY:
			last_log_time = tm.tm_yday;
			break;
		}

		/* 模块初始化成功 */
		logger_init_flag = 1; 
		return 0;

	} while (0);

	/* 出现错误, 回收资源 */
	if (log_thread_lock_init) {
		pthread_mutex_destroy(&pContext->log_thread_lock);
	}

	if (disk_thread_lock_init) {
		pthread_mutex_destroy(&pContext->disk_thread_ctx.disk_thread_lock);
	}

	if (disk_thread_cond_init) {
		pthread_cond_destroy(&pContext->disk_thread_ctx.disk_thread_cond);
	}

	if (pContext->log_buff) {
		free(pContext->log_buff);
	}
	
	if (pContext) {
		free(pContext);
		pContext = NULL;
	}

	return result;
}
Example #15
0
void eMP3Decoder::init_eMP3Decoder(const char* filename)
{
	state=stateInit;

	pthread_mutexattr_t attr;
	pthread_mutexattr_init(&attr);
	pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
	pthread_mutex_init(&lock, &attr);
	pthread_mutexattr_destroy(&attr);

	http=0;

	seekbusy=0;

//	filename="http://205.188.209.193:80/stream/1003";

//	filename="http://sik1.oulu.fi:8002/";
//	filename="http://64.236.34.141:80/stream/1022";
//	filename="http://ios.h07.org:8006/";
//	filename="http://10.0.0.112/join.mp3";
	
	if (strstr(filename, "://")) // assume streaming
	{
		if (!strncmp(filename, "file://", 7))
			filename+=7;
		else
		{
			http=eHTTPConnection::doRequest(filename, this, &error);
			if (!http)
			{
				streamingDone(error);
			} else
			{
				CONNECT(http->transferDone, eMP3Decoder::streamingDone);
				CONNECT(http->createDataSource, eMP3Decoder::createStreamSink);
				http->local_header["User-Agent"]="enigma-mp3/1.0.0";
				http->local_header["Icy-MetaData"]="1"; // enable ICY metadata
				http->start();
				http_status=_("Connecting...");
				filelength=-1;
				handler->messages.send(eServiceHandlerMP3::eMP3DecoderMessage(eServiceHandlerMP3::eMP3DecoderMessage::status));
			}
			filename=0;
		}
	}
	
	if (filename) // not streaming
	{
		sourcefd=::open(filename, O_RDONLY|O_LARGEFILE);
		if (sourcefd<0)
		{
			error=errno;
			eDebug("error opening %s", filename);
			state=stateError;
		} else
		{
			filelength=lseek64(sourcefd, 0, SEEK_END);
			lseek(sourcefd, 0, SEEK_SET);
		}
	} else
		sourcefd=-1;
	
	length=-1;
	Decoder::Flush();
	if (type != codecMPG)
	{
		divisor=1;
		pcmsettings.reconfigure=1;
		dspfd[1]=-1;

		dspfd[0]=::open("/dev/dsp", O_WRONLY|O_NONBLOCK);
		if (dspfd[0]<0)
		{
			eDebug("output failed! (%m)");
			error=errno;
			state=stateError;
		}
	
		if (dspfd[0] >= 0)
		{
			outputsn[0]=new eSocketNotifier(this, dspfd[0], eSocketNotifier::Write, 0);
			CONNECT(outputsn[0]->activated, eMP3Decoder::outputReady);
		} else
			outputsn[0]=0;
		outputsn[1]=0;
	} else
	{
		divisor=1024;
		Decoder::parms.vpid=0x1FFF;
		Decoder::parms.apid=0x1FFF;
		Decoder::parms.pcrpid=-1;
		Decoder::parms.audio_type=DECODE_AUDIO_MPEG;
		Decoder::Set();

		dspfd[0]=::open("/dev/video0", O_WRONLY);
		dspfd[1]=::open("/dev/dsp", O_WRONLY);

		if ((dspfd[0]<0) || (dspfd[1]<0))
		{
			if (dspfd[0]>=0)
				::close(dspfd[0]);
			if (dspfd[1]>=0)
				::close(dspfd[1]);
			eDebug("output failed! (%m)");
			error=errno;
			state=stateError;
			outputsn[0]=0;
			outputsn[1]=0;
		} else

		{
			outputsn[1]=0;
			Decoder::setMpegDevice(dspfd[0]);
			outputsn[0]=new eSocketNotifier(this, dspfd[0], eSocketNotifier::Write, 0);
			CONNECT(outputsn[0]->activated, eMP3Decoder::outputReady);
			outputsn[1]=new eSocketNotifier(this, dspfd[1], eSocketNotifier::Write, 0);
			CONNECT(outputsn[1]->activated, eMP3Decoder::outputReady2);
		}
	}
	if (sourcefd >= 0) // not streaming
	{
		InitCodec(filename);
		if ( type == codecMPG )
		{
			unsigned char buffer[256*1024];
			eString fname=filename;
			off64_t oldpos = lseek64(sourcefd,
				fname.right(4).upper()==".BIN" ? 1024*1024 : 0, SEEK_CUR);
			((eDemux*)audiodecoder)->extractSequenceHeader(buffer, read(sourcefd, buffer, 256*1024));
			lseek64(sourcefd, oldpos, SEEK_SET);
		}
		inputsn=new eSocketNotifier(this, sourcefd, eSocketNotifier::Read, 0);
		CONNECT(inputsn->activated, eMP3Decoder::decodeMore);
	}

	CONNECT(messages.recv_msg, eMP3Decoder::gotMessage);

	maxOutputBufferSize=256*1024;
	minOutputBufferSize=8*1024;

	run();
}
Example #16
0
/* Main entry point. */
int main(int argc, char * argv[])
{
	int ret;
	int sc;
	pthread_mutexattr_t ma;

	testdata_t * td;
	testdata_t alternativ;

	int do_fork;

	pid_t child_pr=0, chkpid;
	int status;
	pthread_t child_th;

	long pshared, mf;

	/* Initialize output */
	output_init();

	/* Test system abilities */
	pshared = sysconf(_SC_THREAD_PROCESS_SHARED);
	mf =sysconf(_SC_MAPPED_FILES);

	#if VERBOSE > 0
	output("Test starting\n");
	output("System abilities:\n");
	output(" TSH : %li\n", pshared);
	output(" MF  : %li\n", mf);
	if ((mf < 0) || (pshared < 0))
		output("Process-shared attributes won't be tested\n");
	#endif

/**********
 * Allocate space for the testdata structure
 */
	if (mf < 0)
	{
		/* Cannot mmap a file (or not interested in this), we use an alternative method */
		td = &alternativ;
		pshared = -1; /* We won't do this testing anyway */
		#if VERBOSE > 0
		output("Testdata allocated in the process memory.\n");
		#endif
	}
	else
	{
		/* We will place the test data in a mmaped file */
		char filename[] = "/tmp/mutex_trylock_2-1-XXXXXX";
		size_t sz;
		void * mmaped;
		int fd;
		char * tmp;

		/* We now create the temp files */
		fd = mkstemp(filename);
		if (fd == -1)
		{ UNRESOLVED(errno, "Temporary file could not be created"); }

		/* and make sure the file will be deleted when closed */
		unlink(filename);

		#if VERBOSE > 1
		output("Temp file created (%s).\n", filename);
		#endif

		sz= (size_t)sysconf(_SC_PAGESIZE);

		tmp = calloc(1, sz);
		if (tmp == NULL)
		{ UNRESOLVED(errno, "Memory allocation failed"); }

		/* Write the data to the file.  */
		if (write (fd, tmp, sz) != (ssize_t) sz)
		{ UNRESOLVED(sz, "Writting to the file failed"); }

		free(tmp);

		/* Now we can map the file in memory */
		mmaped = mmap(NULL, sz, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
		if (mmaped == MAP_FAILED)
		{ UNRESOLVED(errno, "mmap failed"); }

		td = (testdata_t *) mmaped;

		/* Our datatest structure is now in shared memory */
		#if VERBOSE > 1
		output("Testdata allocated in shared memory.\n");
		#endif
	}

/**********
 * For each test scenario, initialize the attributes and other variables.
 * Do the whole thing for each time to test.
 */
	for (sc=0; sc < NSCENAR ; sc++)
	{
		#if VERBOSE > 1
		output("[parent] Preparing attributes for: %s\n", scenarii[sc].descr);
		#endif
		/* set / reset everything */
		do_fork=0;
		ret = pthread_mutexattr_init(&ma);
		if (ret != 0)  {  UNRESOLVED(ret, "[parent] Unable to initialize the mutex attribute object");  }

		/* Set the mutex type */
		ret = pthread_mutexattr_settype(&ma, scenarii[sc].m_type);
		if (ret != 0)  {  UNRESOLVED(ret, "[parent] Unable to set mutex type");  }
		#if VERBOSE > 1
		output("[parent] Mutex type : %i\n", scenarii[sc].m_type);
		#endif

		/* Set the pshared attributes, if supported */
		if ((pshared > 0) && (scenarii[sc].m_pshared != 0))
		{
			ret = pthread_mutexattr_setpshared(&ma, PTHREAD_PROCESS_SHARED);
			if (ret != 0)  {  UNRESOLVED(ret, "[parent] Unable to set the mutex process-shared");  }
			#if VERBOSE > 1
			output("[parent] Mutex is process-shared\n");
			#endif
		}
		#if VERBOSE > 1
		else {
			output("[parent] Mutex is process-private\n");
		}
		#endif

		/* Tell whether the test will be across processes */
		if ((pshared > 0) && (scenarii[sc].fork != 0))
		{
			do_fork = 1;
			#if VERBOSE > 1
			output("[parent] Child will be a new process\n");
			#endif
		}
		#if VERBOSE > 1
		else {
			output("[parent] Child will be a new thread\n");
		}
		#endif

/**********
 * Initialize the testdata_t structure with the previously defined attributes
 */
		/* Initialize the mutex */
		ret = pthread_mutex_init(&(td->mtx), &ma);
		if (ret != 0)
		{  UNRESOLVED(ret, "[parent] Mutex init failed");  }

		/* Initialize the other datas from the test structure */
		td->status=0;

/**********
 * Proceed to the actual testing
 */
		/* Trylock the mutex twice before creating children */
		ret = pthread_mutex_trylock(&(td->mtx));
		if (ret != 0)  {  UNRESOLVED(ret, "[parent] Unable to trylock the mutex");  }
		ret = pthread_mutex_trylock(&(td->mtx));

		if (scenarii[sc].m_type == PTHREAD_MUTEX_RECURSIVE)
		{
			if (ret != 0)  {  FAILED("Failed to pthread_mutex_trylock() twice a recursive mutex");  }

			/* Unlock once so the count is "1" */
			ret = pthread_mutex_unlock(&(td->mtx));
			if (ret != 0)  {  UNRESOLVED(ret, "Failed to unlock the mutex");  }
		}
		else
			if (ret == 0)  {  UNRESOLVED(-1, "Main was able to pthread_mutex_trylock() twice without error");  }

		/* Create the children */
		if (do_fork != 0)
		{
			/* We are testing across processes */
			child_pr = fork();
			if (child_pr == -1)
			{  UNRESOLVED(errno, "[parent] Fork failed");  }

			if (child_pr == 0)
			{
				#if VERBOSE > 3
				output("[child] Child process is starting...\n");
				#endif

				if (tf((void *)td) != NULL)
				{
					UNRESOLVED(-1, "[child] Got an unexpected return value from test function");
				}
				else
				{
					/* We cannot use the PASSED macro here since it would terminate the output */
					exit (0);
				}
			}
			/* Only the parent process goes further */
		}
		else /* do_fork == 0 */
		{
			/* We are testing across two threads */
			ret = pthread_create(&child_th, NULL, tf, td);
			if (ret != 0)  {  UNRESOLVED(ret, "[parent] Unable to create the child thread.");  }
		}

		/* Wait for the child to terminate */
		if (do_fork != 0)
		{
			/* We were testing across processes */
			ret = 0;
			chkpid = waitpid(child_pr, &status, 0);
			if (chkpid != child_pr)
			{
				output("Expected pid: %i. Got %i\n", (int)child_pr, (int)chkpid);
				UNRESOLVED(errno, "Waitpid failed");
			}
			if (WIFSIGNALED(status))
			{
				output("Child process killed with signal %d\n",WTERMSIG(status));
				UNRESOLVED(-1 , "Child process was killed");
			}

			if (WIFEXITED(status))
			{
				ret = WEXITSTATUS(status);
			}
			else
			{
				UNRESOLVED(-1, "Child process was neither killed nor exited");
			}

			if (ret != 0)
			{
				exit(ret); /* Output has already been closed in child */
			}

		}
		else /* child was a thread */
		{
			ret = pthread_join(child_th, NULL);
			if (ret != 0)  {  UNRESOLVED(ret, "[parent] Unable to join the thread");  }
		}

		/* Check the child status */
		if (td->status != EBUSY)
		{
			output("Unexpected return value: %d (%s)\n", td->status, strerror(td->status));
			FAILED("pthread_mutex_trylock() did not return EBUSY in the child");
		}

		/* Unlock the mutex */
		ret= pthread_mutex_unlock(&(td->mtx));
		if (ret != 0)  {  FAILED("Failed to unlock the mutex -- count is broken?");  }

		ret= pthread_mutex_unlock(&(td->mtx));
		if (ret == 0)  {  FAILED("Was able to unlock once more the mutex -- count is broken?");  }

/**********
 * Destroy the data
 */
		ret = pthread_mutex_destroy(&(td->mtx));
		if (ret != 0)  {  UNRESOLVED(ret, "Failed to destroy the mutex");  }

		ret = pthread_mutexattr_destroy(&ma);
		if (ret != 0)  {  UNRESOLVED(ret, "Failed to destroy the mutex attribute object");  }

	}  /* Proceed to the next scenario */

	#if VERBOSE > 0
	output("Test passed\n");
	#endif

	PASSED;
}
int
pthread_mutexattr_setkind_np(pthread_mutexattr_t * attr, int kind)
{
  return pthread_mutexattr_settype( attr, kind );
}
Example #18
0
/**** do_threads_test
 * This function is responsible for all the testing with a given # of threads
 *  nthreads is the amount of threads to create.
 * the return value is:
 *  < 0 if function was not able to create enough threads.
 *  cumulated # of nanoseconds otherwise.
 */
long do_threads_test(int nthreads, mes_t * measure)
{
	int ret;

	int scal, i, j;

	pthread_t *th;

	int s;
	pthread_mutexattr_t ma;
	pthread_condattr_t ca;

	pthread_cond_t cnd;
	pthread_mutex_t mtx;
	int predicate;
	int tnum;

	test_t td;

	struct timespec ts, ts_cumul;

	td.mtx = &mtx;
	td.cnd = &cnd;
	td.predicate = &predicate;
	td.tnum = &tnum;

	/* Allocate space for the threads structures */
	th = (pthread_t *)calloc(nthreads, sizeof(pthread_t));
	if (th == NULL)  {  UNRESOLVED(errno, "Not enough memory for thread storage");  }

	#ifdef PLOT_OUTPUT
	output("%d", nthreads);
	#endif
	/* For each test scenario (mutex and cond attributes) */
	for (s=0; s < NSCENAR ; s++)
	{
		/* Initialize the attributes */
		ret = pthread_mutexattr_init(&ma);
		if (ret != 0)  {  UNRESOLVED(ret, "Unable to initialize mutex attribute object");  }

		ret = pthread_condattr_init(&ca);
		if (ret != 0)  {  UNRESOLVED(ret, "Unable to initialize cond attribute object");  }

		/* Set the attributes according to the scenar and the impl capabilities */
		ret = pthread_mutexattr_settype(&ma, test_scenar[s].mutex_type);
		if (ret != 0)  {  UNRESOLVED(ret, "Unable to set mutex type");  }

		if (pshared_ok > 0)
		{
			ret = pthread_mutexattr_setpshared(&ma, test_scenar[s].pshared);
			if (ret != 0)  {  UNRESOLVED(ret, "Unable to set mutex process-shared");  }

			ret = pthread_condattr_setpshared(&ca, test_scenar[s].pshared);
			if (ret != 0)  {  UNRESOLVED(ret, "Unable to set cond process-shared");  }
		}

		#ifdef USE_ALTCLK
		if (altclk_ok > 0)
		{
			ret = pthread_condattr_setclock(&ca, test_scenar[s].cid);
			if (ret != 0)  {  UNRESOLVED(ret, "Unable to set clock for cond");  }
		}
		#endif

		ts_cumul.tv_sec= 0;
		ts_cumul.tv_nsec=0;

		#if VERBOSE > 1
		output("Starting case %s\n", test_scenar[s].desc);
		#endif

		for (scal=0; scal <  5 * SCALABILITY_FACTOR; scal ++)
		{
			/* Initialize the mutex, the cond, and other data */
			ret = pthread_mutex_init(&mtx, &ma);
			if (ret != 0)  {  UNRESOLVED(ret, "Mutex init failed");  }

			ret = pthread_cond_init(&cnd, &ca);
			if (ret != 0)  {  UNRESOLVED(ret, "Cond init failed");  }

			predicate = 0;
			tnum = 0;

			/* Create the waiter threads */
			for (i=0; i< nthreads; i++)
			{
				ret = pthread_create(&th[i], &ta, waiter, (void *)&td);
				if (ret != 0) /* We reached the limits */
				{
					#if VERBOSE > 1
					output("Limit reached with %i threads\n", i);
					#endif
					#ifdef USE_CANCEL
					for (j = i-1; j>=0; j--)
					{
						ret = pthread_cancel(th[j]);
						if (ret != 0)  {  UNRESOLVED(ret, "Unable to cancel a thread");  }
					}
					#else
					predicate = 1;
					ret = pthread_cond_broadcast(&cnd);
					if (ret != 0)  {  UNRESOLVED(ret, "Unable to broadcast the condition");  }
					#endif
					for (j = i-1; j>=0; j--)
					{
						ret = pthread_join(th[j], NULL);
						if (ret != 0)  {  UNRESOLVED(ret, "Unable to join a canceled thread");  }
					}
					free(th);
					return -1;
				}
			}
			/* All waiter threads are created now */
			#if VERBOSE > 5
			output("%i waiter threads created successfully\n", i);
			#endif

			ret = pthread_mutex_lock(&mtx);
			if (ret != 0)  {  UNRESOLVED(ret, "Unable to lock mutex");  }

			/* Wait for all threads be waiting */
			while (tnum < nthreads)
			{
				ret = pthread_mutex_unlock(&mtx);
				if (ret != 0)  {  UNRESOLVED(ret, "Mutex unlock failed");  }

				sched_yield();

				ret = pthread_mutex_lock(&mtx);
				if (ret != 0)  {  UNRESOLVED(ret, "Mutex lock failed");  }
			}

			/* All threads are now waiting - we do the measure */

			ret = pthread_mutex_unlock(&mtx);
			if (ret != 0)  {  UNRESOLVED(ret, "Mutex unlock failed");  }

			#if VERBOSE > 5
			output("%i waiter threads are waiting; start measure\n", tnum);
			#endif

			do_measure(&mtx, &cnd, test_scenar[s].cid, &ts);

			#if VERBOSE > 5
			output("Measure for %s returned %d.%09d\n", test_scenar[s].desc, ts.tv_sec, ts.tv_nsec);
			#endif

			ts_cumul.tv_sec += ts.tv_sec;
			ts_cumul.tv_nsec += ts.tv_nsec;
			if (ts_cumul.tv_nsec >= 1000000000)
			{
				ts_cumul.tv_nsec -= 1000000000;
				ts_cumul.tv_sec += 1;
			}

			/* We can release the threads */
			predicate = 1;
			ret = pthread_cond_broadcast(&cnd);
			if (ret != 0)  {  UNRESOLVED(ret, "Unable to broadcast the condition");  }

			#if VERBOSE > 5
			output("Joining the waiters...\n");
			#endif

			/* We will join every threads */
			for (i=0; i<nthreads; i++)
			{
				ret = pthread_join(th[i], NULL);
				if (ret != 0)  {  UNRESOLVED(ret, "Unable to join a thread");  }

			}

			/* Destroy everything */
			ret = pthread_mutex_destroy(&mtx);
			if (ret != 0)  {  UNRESOLVED(ret, "Unable to destroy mutex");  }

			ret = pthread_cond_destroy(&cnd);
			if (ret != 0)  {  UNRESOLVED(ret, "Unable to destroy cond");  }
		}

		#ifdef PLOT_OUTPUT
		output(" %d.%09d", ts_cumul.tv_sec, ts_cumul.tv_nsec);
		#endif

		measure->_data[s] = ts_cumul.tv_sec * 1000000 + (ts_cumul.tv_nsec / 1000) ; /* We reduce precision */

		/* Destroy the mutex attributes */
		ret = pthread_mutexattr_destroy(&ma);
		if (ret != 0)  {  UNRESOLVED(ret, "Unable to destroy mutex attribute");  }

		ret = pthread_condattr_destroy(&ca);
		if (ret != 0)  {  UNRESOLVED(ret, "Unable to destroy cond attribute");  }
	}

	/* Free the memory */
	free(th);

	#if VERBOSE > 2
	output("%5d threads; %d.%09d s (%i loops)\n", nthreads, ts_cumul.tv_sec, ts_cumul.tv_nsec, scal);
	#endif

	#ifdef PLOT_OUTPUT
	output("\n");
	#endif

	return ts_cumul.tv_sec * 1000000000 + ts_cumul.tv_nsec;
}
Example #19
0
/** parent thread function **/
int main(int argc, char * argv[])
{
	int ret;
	int i;
	pthread_mutexattr_t ma;
	pthread_t  child;

	output_init();

	#if VERBOSE >1
	output("Initialize the PTHREAD_MUTEX_RECURSIVE mutex\n");
	#endif
	
	/* Initialize the semaphore */
	if ((ret = sem_init(&sem, 0, 0)))
	{  UNRESOLVED(ret, "Sem init failed");  }
	
	/* We initialize the recursive mutex */
	if ((ret = pthread_mutexattr_init(&ma)))
	{  UNRESOLVED(ret, "Mutex attribute init failed");  }
	
	if ((ret = pthread_mutexattr_settype(&ma, PTHREAD_MUTEX_RECURSIVE)))
	{  UNRESOLVED(ret, "Set type RECURSIVE failed");  }
	
	if ((ret = pthread_mutex_init(&mtx, &ma)))
	{  UNRESOLVED(ret, "Recursive mutex init failed");  }
	
	if ((ret = pthread_mutexattr_destroy(&ma)))
	{  UNRESOLVED(ret, "Mutex attribute destroy failed");  }
	
	/* -- The mutex is now ready for testing -- */
	
	/* First, we lock it twice and unlock once */
	if ((ret = pthread_mutex_lock(&mtx)))
	{ UNRESOLVED(ret, "First lock failed");  }
	
	if ((ret = pthread_mutex_lock(&mtx)))
	{ FAILED("Second lock failed");  }


	
	if ((ret = pthread_mutex_unlock(&mtx)))
	{ FAILED("First unlock failed");  }

	#if VERBOSE >1
	output("The mutex has been locked twice and unlocked once, start the thread now.\n");
	#endif
	
	/* Here this thread owns the mutex and the internal count is "1" */
	
	/* We create the child thread */
	if ((ret = pthread_create(&child, NULL, threaded, NULL)))
	{  UNRESOLVED(ret, "Unable to create child thread");  }
	
	/* then wait for child to be ready */
	if ((ret = sem_wait(&sem)))
	{  UNRESOLVED(errno, "Wait sem in child failed");  }

	#if VERBOSE >1
	output("[main] unlock the mutex.\n");
	#endif
	
	/* We can now unlock the mutex */
	if ((ret = pthread_mutex_unlock(&mtx)))
	{ FAILED("Second unlock failed");  }

	/* We wait for the child to lock the mutex */
	if ((ret = sem_wait(&sem)))
	{  UNRESOLVED(errno, "Wait sem in child failed");  }

	/* Then, try to unlock the mutex (owned by the child or unlocked) */
	ret = pthread_mutex_unlock(&mtx);
	if (ret == 0)
	{ FAILED("Unlock of unowned mutex succeeds");  }
	
	/* Everything seems OK here */
	if ((ret = pthread_join(child, NULL)))
	{  UNRESOLVED(ret, "Child join failed");  }
	
	/* Simple loop to double-check */
	#if VERBOSE >1
	output("[main] joined the thread.\n");
	output("Lock & unlock the mutex 50 times.\n");
	#endif

	for (i=0; i<50; i++)
	{
		if ((ret = pthread_mutex_lock(&mtx)))
		{  FAILED("Lock failed in loop");  }
	}
	for (i=0; i<50; i++)
	{
		if ((ret = pthread_mutex_unlock(&mtx)))
		{  FAILED("Unlock failed in loop");  }
	}
	
	ret = pthread_mutex_unlock(&mtx);
	if (ret == 0)
	{  FAILED("Unlock succeeds after the loop");  }
	
	#if VERBOSE >1
	output("Everything went OK; destroy the mutex.\n");
	#endif
	/* The test passed, we destroy the mutex */
	if ((ret = pthread_mutex_destroy(&mtx)))
	{  UNRESOLVED(ret, "Final mutex destroy failed");  }
	
	PASSED;
}
Example #20
0
/***********************************************************************
 *              create_surface
 */
struct window_surface *create_surface(macdrv_window window, const RECT *rect,
                                      struct window_surface *old_surface, BOOL use_alpha)
{
    struct macdrv_window_surface *surface;
    struct macdrv_window_surface *old_mac_surface = get_mac_surface(old_surface);
    int width = rect->right - rect->left, height = rect->bottom - rect->top;
    DWORD *colors;
    pthread_mutexattr_t attr;
    int err;
    DWORD window_background;

    surface = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
                        FIELD_OFFSET(struct macdrv_window_surface, info.bmiColors[3]));
    if (!surface) return NULL;

    err = pthread_mutexattr_init(&attr);
    if (!err)
    {
        err = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
        if (!err)
            err = pthread_mutex_init(&surface->mutex, &attr);
        pthread_mutexattr_destroy(&attr);
    }
    if (err)
    {
        HeapFree(GetProcessHeap(), 0, surface);
        return NULL;
    }

    surface->info.bmiHeader.biSize        = sizeof(surface->info.bmiHeader);
    surface->info.bmiHeader.biWidth       = width;
    surface->info.bmiHeader.biHeight      = height; /* bottom-up */
    surface->info.bmiHeader.biPlanes      = 1;
    surface->info.bmiHeader.biBitCount    = 32;
    surface->info.bmiHeader.biSizeImage   = get_dib_image_size(&surface->info);
    surface->info.bmiHeader.biCompression = BI_RGB;
    surface->info.bmiHeader.biClrUsed     = 0;

    colors = (DWORD *)((char *)&surface->info + surface->info.bmiHeader.biSize);
    colors[0] = 0x00ff0000;
    colors[1] = 0x0000ff00;
    colors[2] = 0x000000ff;

    surface->header.funcs = &macdrv_surface_funcs;
    surface->header.rect  = *rect;
    surface->header.ref   = 1;
    surface->window = window;
    reset_bounds(&surface->bounds);
    if (old_mac_surface && old_mac_surface->drawn)
    {
        surface->drawn = CreateRectRgnIndirect(rect);
        OffsetRgn(surface->drawn, -rect->left, -rect->top);
        if (CombineRgn(surface->drawn, surface->drawn, old_mac_surface->drawn, RGN_AND) <= NULLREGION)
        {
            DeleteObject(surface->drawn);
            surface->drawn = 0;
        }
    }
    update_blit_data(surface);
    surface->use_alpha = use_alpha;
    surface->bits = HeapAlloc(GetProcessHeap(), 0, surface->info.bmiHeader.biSizeImage);
    if (!surface->bits) goto failed;
    window_background = macdrv_window_background_color();
    memset_pattern4(surface->bits, &window_background, surface->info.bmiHeader.biSizeImage);

    TRACE("created %p for %p %s bits %p-%p\n", surface, window, wine_dbgstr_rect(rect),
          surface->bits, surface->bits + surface->info.bmiHeader.biSizeImage);

    return &surface->header;

failed:
    macdrv_surface_destroy(&surface->header);
    return NULL;
}
int OSAL_create_mutex(OSAL_mutex_t *pmtx, int owned, char * name)
{

#ifndef WIMAX_SYS_WINDOWS 
	int ret = -1;
	pthread_mutexattr_t mtxAttr;
	pthread_mutex_t mtx;
	int b_attr_inited = 0;

	//int oflag = O_CREAT;		// create if not existent else open it.
	//mode_t mode = S_IRWXU;		// read, write, execute

	struct mutex_internal *p_int_mtx = NULL;

	OSALTRACE(OSAL_DEBUG, ("enter. owned: %d", owned));

	if ( pmtx == NULL )
		goto exit;

	if (name != NULL)
		return OSAL_create_named_mutex(pmtx, owned, name);


	if ((ret = pthread_mutexattr_init(&mtxAttr)) != 0) {
		OSALTRACE(OSAL_ERROR,
			  ("exit - mutexattr_init failed. return: %d", ret));
		goto exit;
	}

	b_attr_inited = 1;

	// Set type appropriate for windows style semantics for Mutexes
	pthread_mutexattr_settype(&mtxAttr, PTHREAD_MUTEX_RECURSIVE_NP);

	if ((ret = pthread_mutex_init(&mtx, &mtxAttr)) != 0) {

		OSALTRACE(OSAL_ERROR,
			  ("exit - failure. mutex_init return code: %d", ret));
		goto exit;
	}


	if ( owned )
		pthread_mutex_lock(&mtx);

	// Mutex type is a complex structure and needs to be handled like this.
	// We will allocate it and hang on to the ptr
	p_int_mtx = (struct mutex_internal *)calloc(1, sizeof(struct mutex_internal));
	if (p_int_mtx != NULL)
	{
		p_int_mtx->mtx = mtx;
	}
	else
	{
		// error return...
		pthread_mutex_destroy(&mtx);
		OSALTRACE(OSAL_ERROR, ("exit - failure. mem alloc failed"));

		// TODO :: set the errno correctly to reflect out of memory condition
		ret = -1;
	}

	*pmtx = (void *)p_int_mtx;

exit:
	if ( b_attr_inited )
		pthread_mutexattr_destroy(&mtxAttr);
		
	return ret;
#else

#endif
}
short TU_Mutex_pthread::Init_Mutex()
{
        // Check for pthreads.
        if ((this->lib.bIsPlugin != TU_LibID_pthreads.bIsPlugin) ||
	    (this->lib.Name == NULL) || (strcmp(this->lib.Name, TU_LibID_pthreads.Name) != 0))    // PThreads ID.
        {
                // Trying to use incorrect library abort.
                return -1;
        }

        // Check and see if the mutex is already inited.
        if (this->mutex_init)
        {
                // Error, mutex must not be inited.
                return -4;
        }
        else
        {
                // Check and see if the attribs object is inited.
                if (this->attrib_init)
                {
                        // Check and see if the attribs object was specified by the user.
                        if (!this->user_attrib)
                        {
                                // We need to destroy the attribs object first.
                                this->rc_from_prevOP = pthread_mutexattr_destroy(&attribs);

                                // Check for error.
                                if (this->rc_from_prevOP)
                                {
                                        // An error occured.
                                        return -5;
                                }

                                // Set attrib_init to false.
                                this->attrib_init = false;
                        }
                }

                // Init the attribs object.
                // Note: if statement used due to the above if statement possibly destroying the attribs object.
                if (!this->attrib_init)
                {
                        // Init attribs.
                        this->rc_from_prevOP = pthread_mutexattr_init(&attribs);

                        // Check for error.
                        if (this->rc_from_prevOP)
                        {
                                // An error occured.
                                return -5;
                        }

                        // Set the type to errorcheck.
                        this->rc_from_prevOP = pthread_mutexattr_settype(&attribs, PTHREAD_MUTEX_ERRORCHECK);

                        // Check for error.
                        if (this->rc_from_prevOP)
                        {
                                // An error occured.
                                return -5;
                        }

                        // Set attrib init.
                        this->attrib_init = true;
                }

                // Init the actual mutex.
                this->rc_from_prevOP = pthread_mutex_init(&mutex, &attribs);

                // Check for error.
                if (this->rc_from_prevOP)
                {
                        // An error occured.
                        return -5;
                }

                // Set mutex init.
                this->mutex_init = true;
        }

        // Exit function.
        return 0;
}
Example #23
0
	Mutex::Mutex(MUTEX_TYPE type)
	{
		pthread_mutexattr_init(&m_attr);
		pthread_mutexattr_settype(&m_attr, type);
		pthread_mutex_init(&m_mutex, &m_attr);
	}
Example #24
0
File: 1-2.c Project: Nan619/ltp-ddt
int main(int argc, char *argv[])
{
	int ret;

	pthread_mutexattr_t ma;
	pthread_condattr_t ca;

	int scenar;
	long pshared, monotonic, cs, mf;

	pid_t p_child[NTHREADS];
	pthread_t t_child[NTHREADS];
	int ch;
	pid_t pid;
	int status;

	pthread_t t_timer;

	testdata_t alternativ;

	output_init();

	/* check the system abilities */
	pshared = sysconf(_SC_THREAD_PROCESS_SHARED);
	cs = sysconf(_SC_CLOCK_SELECTION);
	monotonic = sysconf(_SC_MONOTONIC_CLOCK);
	mf = sysconf(_SC_MAPPED_FILES);

#if VERBOSE > 0
	output("Test starting\n");
	output("System abilities:\n");
	output(" TPS : %li\n", pshared);
	output(" CS  : %li\n", cs);
	output(" MON : %li\n", monotonic);
	output(" MF  : %li\n", mf);
	if ((mf < 0) || (pshared < 0))
		output("Process-shared attributes won't be tested\n");
	if ((cs < 0) || (monotonic < 0))
		output("Alternative clock won't be tested\n");
#endif

	/* We are not interested in testing the clock if we have no other clock available.. */
	if (monotonic < 0)
		cs = -1;

#ifndef USE_ALTCLK
	if (cs > 0)
		output
		    ("Implementation supports the MONOTONIC CLOCK but option is disabled in test.\n");
#endif

/**********
 * Allocate space for the testdata structure
 */
	if (mf < 0) {
		/* Cannot mmap a file, we use an alternative method */
		td = &alternativ;
		pshared = -1;	/* We won't do this testing anyway */
#if VERBOSE > 0
		output("Testdata allocated in the process memory.\n");
#endif
	} else {
		/* We will place the test data in a mmaped file */
		char filename[] = "/tmp/cond_wait_stress-XXXXXX";
		size_t sz, ps;
		void *mmaped;
		int fd;
		char *tmp;

		/* We now create the temp files */
		fd = mkstemp(filename);
		if (fd == -1) {
			UNRESOLVED(errno,
				   "Temporary file could not be created");
		}

		/* and make sure the file will be deleted when closed */
		unlink(filename);

#if VERBOSE > 1
		output("Temp file created (%s).\n", filename);
#endif

		ps = (size_t) sysconf(_SC_PAGESIZE);
		sz = ((sizeof(testdata_t) / ps) + 1) * ps;	/* # pages needed to store the testdata */

		tmp = calloc(1, sz);
		if (tmp == NULL) {
			UNRESOLVED(errno, "Memory allocation failed");
		}

		/* Write the data to the file.  */
		if (write(fd, tmp, sz) != (ssize_t) sz) {
			UNRESOLVED(sz, "Writting to the file failed");
		}

		free(tmp);

		/* Now we can map the file in memory */
		mmaped =
		    mmap(NULL, sz, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
		if (mmaped == MAP_FAILED) {
			UNRESOLVED(errno, "mmap failed");
		}

		td = (testdata_t *) mmaped;

		/* Our datatest structure is now in shared memory */
#if VERBOSE > 1
		output("Testdata allocated in shared memory (%ib).\n",
		       sizeof(testdata_t));
#endif
	}

	/* Do the test for each test scenario */
	for (scenar = 0; scenar < NSCENAR; scenar++) {
		/* set / reset everything */
		td->fork = 0;
		ret = pthread_mutexattr_init(&ma);
		if (ret != 0) {
			UNRESOLVED(ret,
				   "[parent] Unable to initialize the mutex attribute object");
		}
		ret = pthread_condattr_init(&ca);
		if (ret != 0) {
			UNRESOLVED(ret,
				   "[parent] Unable to initialize the cond attribute object");
		}
#ifndef WITHOUT_XOPEN
		/* Set the mutex type */
		ret = pthread_mutexattr_settype(&ma, scenarii[scenar].m_type);
		if (ret != 0) {
			UNRESOLVED(ret, "[parent] Unable to set mutex type");
		}
#endif

		/* Set the pshared attributes, if supported */
		if ((pshared > 0) && (scenarii[scenar].mc_pshared != 0)) {
			ret =
			    pthread_mutexattr_setpshared(&ma,
							 PTHREAD_PROCESS_SHARED);
			if (ret != 0) {
				UNRESOLVED(ret,
					   "[parent] Unable to set the mutex process-shared");
			}
			ret =
			    pthread_condattr_setpshared(&ca,
							PTHREAD_PROCESS_SHARED);
			if (ret != 0) {
				UNRESOLVED(ret,
					   "[parent] Unable to set the cond var process-shared");
			}
		}

		/* Set the alternative clock, if supported */
#ifdef USE_ALTCLK
		if ((cs > 0) && (scenarii[scenar].c_clock != 0)) {
			ret = pthread_condattr_setclock(&ca, CLOCK_MONOTONIC);
			if (ret != 0) {
				UNRESOLVED(ret,
					   "[parent] Unable to set the monotonic clock for the cond");
			}
		}
		ret = pthread_condattr_getclock(&ca, &td->cid);
		if (ret != 0) {
			UNRESOLVED(ret, "Unable to get clock from cond attr");
		}
#else
		td->cid = CLOCK_REALTIME;
#endif

		/* Tell whether the test will be across processes */
		if ((pshared > 0) && (scenarii[scenar].fork != 0)) {
			td->fork = 1;
		}

		/* initialize the condvar */
		ret = pthread_cond_init(&td->cnd, &ca);
		if (ret != 0) {
			UNRESOLVED(ret, "Cond init failed");
		}

		/* initialize the mutex */
		ret = pthread_mutex_init(&td->mtx, &ma);
		if (ret != 0) {
			UNRESOLVED(ret, "Mutex init failed");
		}

		/* Destroy the attributes */
		ret = pthread_condattr_destroy(&ca);
		if (ret != 0) {
			UNRESOLVED(ret,
				   "Failed to destroy the cond var attribute object");
		}

		ret = pthread_mutexattr_destroy(&ma);
		if (ret != 0) {
			UNRESOLVED(ret,
				   "Failed to destroy the mutex attribute object");
		}
#if VERBOSE > 2
		output("[parent] Starting test %s\n", scenarii[scenar].descr);
#endif

		td->count = 0;
		/* Create all the children */
		for (ch = 0; ch < NTHREADS; ch++) {
			if (td->fork == 0) {
				ret =
				    pthread_create(&t_child[ch], NULL, child,
						   NULL);
				if (ret != 0) {
					UNRESOLVED(ret,
						   "Failed to create a child thread");
				}
			} else {
				p_child[ch] = fork();
				if (p_child[ch] == -1) {
					ret = errno;
					for (--ch; ch >= 0; ch--)
						kill(p_child[ch], SIGKILL);
					UNRESOLVED(ret,
						   "Failed to create a child process");
				}

				if (p_child[ch] == 0) {	/* We are the child */
					child(NULL);
					exit(0);
				}
			}
		}
#if VERBOSE > 4
		output("[parent] All children are running\n");
#endif

		/* Make sure all children are waiting */
		ret = pthread_mutex_lock(&td->mtx);
		if (ret != 0) {
			UNRESOLVED_KILLALL(ret, "Failed to lock mutex",
					   p_child);
		}
		ch = td->count;
		while (ch < NTHREADS) {
			ret = pthread_mutex_unlock(&td->mtx);
			if (ret != 0) {
				UNRESOLVED_KILLALL(ret,
						   "Failed to unlock mutex",
						   p_child);
			}
			sched_yield();
			ret = pthread_mutex_lock(&td->mtx);
			if (ret != 0) {
				UNRESOLVED_KILLALL(ret, "Failed to lock mutex",
						   p_child);
			}
			ch = td->count;
		}

#if VERBOSE > 4
		output("[parent] All children are waiting\n");
#endif

		/* create the timeout thread */
		ret = pthread_create(&t_timer, NULL, timer, p_child);
		if (ret != 0) {
			UNRESOLVED_KILLALL(ret, "Unable to create timer thread",
					   p_child);
		}

		/* Wakeup the children */
		td->predicate = 1;
		ret = pthread_cond_signal(&td->cnd);
		if (ret != 0) {
			UNRESOLVED_KILLALL(ret,
					   "Failed to signal the condition.",
					   p_child);
		}
#if VERBOSE > 4
		output("[parent] Condition was signaled\n");
#endif

		ret = pthread_mutex_unlock(&td->mtx);
		if (ret != 0) {
			UNRESOLVED_KILLALL(ret, "Failed to unlock mutex",
					   p_child);
		}
#if VERBOSE > 4
		output("[parent] Joining the children\n");
#endif

		/* join the children */
		for (ch = (NTHREADS - 1); ch >= 0; ch--) {
			if (td->fork == 0) {
				ret = pthread_join(t_child[ch], NULL);
				if (ret != 0) {
					UNRESOLVED(ret,
						   "Failed to join a child thread");
				}
			} else {
				pid = waitpid(p_child[ch], &status, 0);
				if (pid != p_child[ch]) {
					ret = errno;
					output
					    ("Waitpid failed (expected: %i, got: %i)\n",
					     p_child[ch], pid);
					for (; ch >= 0; ch--) {
						kill(p_child[ch], SIGKILL);
					}
					UNRESOLVED(ret, "Waitpid failed");
				}
				if (WIFEXITED(status)) {
					/* the child should return only failed or unresolved or passed */
					if (ret != PTS_FAIL)
						ret |= WEXITSTATUS(status);
				}
			}
		}
		if (ret != 0) {
			output_fini();
			exit(ret);
		}
#if VERBOSE > 4
		output("[parent] All children terminated\n");
#endif

		/* cancel the timeout thread */
		ret = pthread_cancel(t_timer);
		if (ret != 0) {
			/* Strange error here... the thread cannot be terminated (app would be killed) */
			UNRESOLVED(ret, "Failed to cancel the timeout handler");
		}

		/* join the timeout thread */
		ret = pthread_join(t_timer, NULL);
		if (ret != 0) {
			UNRESOLVED(ret, "Failed to join the timeout handler");
		}

		/* Destroy the datas */
		ret = pthread_cond_destroy(&td->cnd);
		if (ret != 0) {
			UNRESOLVED(ret, "Failed to destroy the condvar");
		}

		ret = pthread_mutex_destroy(&td->mtx);
		if (ret != 0) {
			UNRESOLVED(ret, "Failed to destroy the mutex");
		}

	}

	/* exit */
	PASSED;
}
Example #25
0
static int
do_test (void)
{
  pthread_mutexattr_t ma;
  int err;
  struct timespec ts;
  struct timeval tv;

  if (pthread_mutexattr_init (&ma) != 0)
    {
      puts ("mutexattr_init failed");
      exit (1);
    }

  if (pthread_mutexattr_settype (&ma, PTHREAD_MUTEX_ERRORCHECK) != 0)
    {
      puts ("mutexattr_settype failed");
      exit (1);
    }

  if (pthread_mutex_init (&mut, &ma) != 0)
    {
      puts ("mutex_init failed");
      exit (1);
    }

  /* Get the mutex.  */
  if (pthread_mutex_lock (&mut) != 0)
    {
      puts ("mutex_lock failed");
      exit (1);
    }

  /* Waiting for the condition will fail.  But we want the timeout here.  */
  if (gettimeofday (&tv, NULL) != 0)
    {
      puts ("gettimeofday failed");
      exit (1);
    }

  TIMEVAL_TO_TIMESPEC (&tv, &ts);
  ts.tv_nsec += 500000000;
  if (ts.tv_nsec >= 1000000000)
    {
      ts.tv_nsec -= 1000000000;
      ++ts.tv_sec;
    }
  err = pthread_cond_timedwait (&cond, &mut, &ts);
  if (err == 0)
    {
      /* This could in theory happen but here without any signal and
	 additional waiter it should not.  */
      puts ("cond_timedwait succeeded");
      exit (1);
    }
  else if (err != ETIMEDOUT)
    {
      printf ("cond_timedwait returned with %s\n", strerror (err));
      exit (1);
    }

  err = pthread_mutex_unlock (&mut);
  if (err != 0)
    {
      printf ("mutex_unlock failed: %s\n", strerror (err));
      exit (1);
    }

  return 0;
}
int main(void) {
	int i, j, k;
	double time;
	FILE *output;
	long thread, thread_c = 0;
	pthread_t *thread_handles;
	struct timeval lt, ll;
	int my_position;	

	//Muttex init
	pthread_mutexattr_init(&attr);
	pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_TIMED_NP);
	pthread_mutex_init(&lock, &attr);

	//Thread init
	thread_handles = (pthread_t *)malloc(num_of_threads*sizeof(pthread_t));



	/* allocate memory and read input data */
	read_world();
	change_list = (cells**)malloc(sizeof(cells*)* world_size*world_size*world_size);
	next_change_list = (cells**)malloc(sizeof(cells*)* world_size*world_size*world_size);

	/* set timer */
	gettimeofday(&lt, NULL);

	/* core part */
	init_change_list();	
	//clock_t start = clock();
	/* Whole lifecycle. hehe */
	for (i = 0; i < num_of_steps; i++)
	{
		printf("Generation number %d\n", i);
		size_to_handle = 1 + ((change_list_size - 1) / num_of_threads); //Single part to solve
		
		/*Update generation and every single neighbour count joint to change of state*/
		for (thread = 0; thread < num_of_threads; thread++)
		{
			pthread_create(&thread_handles[thread], NULL, next_generation, (void *)thread);
		}
		for (thread = 0; thread < num_of_threads; thread++)
		{
			pthread_join(thread_handles[thread], NULL);
		}

		/* Create new change list */
		for (thread = 0; thread < num_of_threads; thread++)
		{
			pthread_create(&thread_handles[thread], NULL, next_change_list_cr, (void *)thread);
		}
		for (thread = 0; thread < num_of_threads; thread++)
		{
			pthread_join(thread_handles[thread], NULL);
		}
		
		/* Copy next change list into change list */
		/*change_list = next_change_list;
		for (int  n= 0; n < next_change_list_size; n++)
		{
			change_list[n] = next_change_list[n];
		}*/
		//clock_t memstart = clock();
		
		memcpy(change_list, next_change_list, next_change_list_size*sizeof(cells**));
		
	//	clock_t memfinish = clock();
	//	float memtime = (float)(memfinish - memstart)/CLOCKS_PER_SEC;
	//	printf("time %f\n", memtime);

		//Reset for next generation
		change_list_size = next_change_list_size;
		next_change_list_size = 0;		
		if (change_list_size == 0){
			break;
		}
				
	}
//	clock_t end = clock();
//	float seconds = (float)(end - start) / CLOCKS_PER_SEC;
//	printf("time %f", seconds);
	/* set timer and print measured time*/

	gettimeofday(&ll, NULL);
	time = (double)(ll.tv_sec - lt.tv_sec) + (double)(ll.tv_usec - lt.tv_usec) / 1000000.0;
	fprintf(stderr, "Time : %.6lf\n", time);

	/* write output file */

	output = fopen("output.life", "w");
	fprintf(output, "%d %d %d %d %d %d %d\n", world_size, D1, D2, L1, L2, num_of_steps, num_of_threads);
	for (i = 0; i < world_size; i++)
	{
		for (j = 0; j < world_size; j++)
		{
			for (k = 0; k < world_size; k++)
			{
				fprintf(output, "%d ", cube[i][j][k].status);
			}
			fprintf(output, "\n");
		}
	}	
	fclose(output);	
	return 0;
}
/*!-----------------------------------------------------------------------

TODO: FIX!
    s m _ i n i t i a l i z e _ s y s

    @brief Initialize the data structures in a new shared memory segment.

    The specified file (referenced by the supplied file descriptor) will be
    mapped into virtual memory and the size of the file adjusted to match the
    desired size of the shared memory segment.

    This function will set up all of the data structures in the shared memory
    segment for use.  This function should be called after a brand new shared
    memory segment has been created and opened on disk.  This function should
    not be called on an existing shared memory segment that contains data as
    all of that data will be deleted by this function.

    @param[in] fd - The file descriptor of the file associated with this
               shared memory segment.

    @param[in] sharedMemorySegmentSize - The size of the shared memory
               segment in bytes.

    @return The new memory address of where the shared memory segment begins.
            On error, a null pointer is returned and errno will be set to
            indicate the error that was encountered.

------------------------------------------------------------------------*/
sysMemory_t* sm_initialize_sys ( int fd, size_t sharedMemorySegmentSize )
{
    int          status;
    sysMemory_t* sharedMemory;

    LOG ( "Initializing system shared memory - fd[%d], Size[%'lu]\n", fd,
          sharedMemorySegmentSize );
    //
    //  Map the shared memory file into virtual memory.
    //
    sharedMemory = mmap ( NULL, SYS_INITIAL_SHARED_MEMORY_SIZE,
                          PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0 );
    if ( sharedMemory == MAP_FAILED )
    {
        printf ( "Unable to map the system shared memory segment. errno: %u[%m].\n",
                 errno );
        return 0;
    }
    //
    //  Make the pseudo-file for the shared memory segment the size of the
    //  shared memory segment.  Note that this will destroy any existing data
    //  if the segment already exists.
    //
    status = ftruncate ( fd, SYS_INITIAL_SHARED_MEMORY_SIZE );
    if (status != 0)
    {
        printf ( "Unable to resize the system shared memory segment to [%lu] "
                 "bytes - errno: %u[%m].\n", SYS_INITIAL_SHARED_MEMORY_SIZE,
                  errno );
        return 0;
    }
    //
    //  Set all of the data in this shared memory segment to zero.
    //
    // TODO: (void)memset ( sharedMemory, 0, sharedMemorySegmentSize );
    (void)memset ( sharedMemory, 0xbb, sharedMemorySegmentSize );

    //
    //  Initialize our global pointer to the shared memory segment.
    //
    sysControl = sharedMemory;

    //
    //  Initialize the fields in the shared memory control structure.  This
    //  structure is located at the beginning of the shared memory region that
    //  we just created and the fields here are adjusted to take into account
    //  the size of the system shared memory structure.
    //
    sysControl->sharedMemorySegmentSize = sharedMemorySegmentSize;
    sysControl->currentOffset           = sysSize;
    sysControl->currentSize             = sharedMemorySegmentSize - sysSize;
    sysControl->systemInitialized       = 0;

    //
    //  Create the mutex attribute initializer that we can use to initialize
    //  all of the mutexes in the B-trees.
    //
    pthread_mutexattr_t* mutexAttributes = &sysControl->masterMutexAttributes;

    status =  pthread_mutexattr_init ( mutexAttributes );
    if ( status != 0 )
    {
        printf ( "Unable to initialize system mutex attributes - errno: %u[%m].\n",
                 status );
        return 0;
    }
    //
    // Set this mutex to be a process shared mutex.
    //
    status = pthread_mutexattr_setpshared ( mutexAttributes,
                                            PTHREAD_PROCESS_SHARED );
    if ( status != 0 )
    {
        printf ( "Unable to set system shared mutex attribute - errno: %u[%m].\n",
                 status );
        return 0;
    }
    //
    // Set this mutex to be a recursive mutex.
    //
    status = pthread_mutexattr_settype ( mutexAttributes,
                                         PTHREAD_MUTEX_RECURSIVE );
    if ( status != 0 )
    {
        printf ( "Unable to set system recursive mutex attribute - errno: %u[%m].\n",
                 status );
        return 0;
    }
    //
    //  Initialize the shared memory mutex.
    //
    status = pthread_mutex_init ( &sysControl->sysLock, mutexAttributes );
    if ( status != 0 )
    {
        printf ( "Unable to initialize system shared memory manager mutex - errno: "
                 "%u[%m].\n", status );
        return 0;
    }
    //
    //  Now we can divide up the rest of the system shared memory segment into
    //  the free B-tree blocks list.
    //
    //  We do this by creating a singly linked list of blocks using the blocks
    //  themselves containing the offset to the next block.
    //
    //  Now compute the size of each node in the system B-trees...
    //
    //  If the user specified an even number of records, increment it to be an
    //  odd number.  The btree algorithm here only operates correctly if the
    //  record count is odd.
    //
    unsigned int maxRecordsPerNode = SYS_RECORD_COUNT;

    if ( ( maxRecordsPerNode & 1 ) == 0 )
    {
        maxRecordsPerNode++;
    }
    //
    //  Compute the node size as the btree node header size plus the size of
    //  the record offset area plus the link offfset area.
    //
    unsigned int nodeSize = sN + ( maxRecordsPerNode * sO ) +
                            ( ( maxRecordsPerNode + 1 ) * sO );
    //
    //  Round up the node size to the next multiple of 8 bytes to maintain
    //  long int alignment in the structures.
    //
    nodeSize = ( nodeSize + 7 ) & 0xfffffff8;

    //
    //  Round up the current free memory offset to the next multiple of 8
    //  bytes.
    //
    offset_t currentOffset = ( sysControl->currentOffset + 7 ) & 0xfffffff8;

    //
    //  Adjust the number of bytes of free memory available after the rounding
    //  up of the offset above.
    //
    unsigned int currentSize =
        sysControl->currentSize - ( currentOffset - sysControl->currentOffset );

    //
    //  Initialize the free list head offset to point to the first block in
    //  our free list.
    //
    sysControl->freeListHead = currentOffset;

    //
    //  Initialize the free list block counter.
    //
    sysControl->freeListCount = 0;

    //
    //  Get the pointer to the first free memory block.
    //
    void* currentPtr = (void*)sysControl + sysSize;

    //
    //  while we have not exhausted the amount of memory in this shared memory
    //  segment...
    //
    offset_t workingOffset = currentOffset;
    while ( currentSize >= nodeSize )
    {
        //
        //  Store the offset to the next block in the current block.
        //
        workingOffset += nodeSize;
        *(offset_t*)currentPtr = workingOffset;

        //
        //  Increment the current memory pointer and decrement the amount of
        //  space we still have left.
        //
        currentPtr  += nodeSize;
        currentSize -= nodeSize;

        //
        //  Increment the number of blocks in the free list.
        //
        ++sysControl->freeListCount;
    }
    //
    //  We have finished setting up the list of free blocks so set the tail
    //  pointer to point to the last block and mark the last block with the
    //  NULL offset value.
    //
    sysControl->freeListTail = workingOffset;
    *(offset_t*)currentPtr = 0;

    //
    //  Set the "initialized" flag to indicate that the shared memory
    //  allocation system is in a usable state.  Note that this indicator is
    //  primarily used by the sm_malloc function to determine how to allocate
    //  memory for the shared memory memory management function B-trees that
    //  we just defined above.
    //
    sysControl->systemInitialized = 1;

    //
    //  Initialize the 2 sets of data structures defined in the system shared
    //  memory segment that we will need in order to create the system B-trees
    //  that come next.
    //
    //  These data structures were allocated in the definition of the
    //  sysMemory_t object typedef but we need to fill them in since the
    //  compiler can't do the runtime initialization of these.
    //
    sysControl->sizeKeyDef.fieldCount = 2;
    sysControl->sizeFieldDef1.type   = ft_ulong;
    sysControl->sizeFieldDef1.offset = offsetof ( memoryChunk_t, segmentSize );
    sysControl->sizeFieldDef1.size   = 1;
    sysControl->sizeFieldDef2.type   = ft_ulong;
    sysControl->sizeFieldDef2.offset = offsetof ( memoryChunk_t, offset );
    sysControl->sizeFieldDef2.size   = 1;

    sysControl->offsetKeyDef.fieldCount = 1;
    sysControl->offsetFieldDef.type   = ft_ulong;
    sysControl->offsetFieldDef.offset = offsetof ( memoryChunk_t, offset );
    sysControl->offsetFieldDef.size   = 1;

    //
    //  Now go initialize the 2 B-trees that will be used to perform the
    //  memory management in the user shared memory segment.
    //
    sysControl->availableMemoryBySize.type = TYPE_SYSTEM;
    btree_create_sys ( &sysControl->availableMemoryBySize,
                       SYS_RECORD_COUNT,
                       &sysControl->sizeKeyDef );

    sysControl->availableMemoryByOffset.type = TYPE_SYSTEM;
    btree_create_sys ( &sysControl->availableMemoryByOffset,
                       SYS_RECORD_COUNT,
                       &sysControl->offsetKeyDef );
    //
    //  Let the user know that the system initialization has been completed.
    //
    LOG ( "\n===== System shared memory is Initialized at %p =====\n\n",
          sysControl );
    //
    //  Return the address of the shared memory segment to the caller.
    //
    return sharedMemory;
}
Example #28
0
static void _init_attr()
{
    pthread_mutexattr_init(&_attr);
    pthread_mutexattr_settype(&_attr, PTHREAD_MUTEX_RECURSIVE);
}
Example #29
0
int guac_client_init(guac_client* client, int argc, char** argv) {

    rdp_guac_client_data* guac_client_data;

    freerdp* rdp_inst;
    rdpSettings* settings;

    char* hostname;
    int port = RDP_DEFAULT_PORT;
    boolean bitmap_cache;

    /**
     * Selected server-side keymap. Client will be assumed to also use this
     * keymap. Keys will be sent to server based on client input on a
     * best-effort basis.
     */
    const guac_rdp_keymap* chosen_keymap;

    if (argc < RDP_ARGS_COUNT) {

        guac_protocol_send_error(client->socket,
                                 "Wrong argument count received.");
        guac_socket_flush(client->socket);

        guac_error = GUAC_STATUS_BAD_ARGUMENT;
        guac_error_message = "Wrong argument count received";

        return 1;
    }

    /* If port specified, use it */
    if (argv[IDX_PORT][0] != '\0')
        port = atoi(argv[IDX_PORT]);

    hostname = argv[IDX_HOSTNAME];

    /* Allocate client data */
    guac_client_data = malloc(sizeof(rdp_guac_client_data));

    /* Init random number generator */
    srandom(time(NULL));

    /* Init client */
    freerdp_channels_global_init();
    rdp_inst = freerdp_new();
    rdp_inst->PreConnect = rdp_freerdp_pre_connect;
    rdp_inst->PostConnect = rdp_freerdp_post_connect;
    rdp_inst->ReceiveChannelData = __guac_receive_channel_data;

    /* Allocate FreeRDP context */
    rdp_inst->context_size = sizeof(rdp_freerdp_context);
    rdp_inst->ContextNew  = (pContextNew) rdp_freerdp_context_new;
    rdp_inst->ContextFree = (pContextFree) rdp_freerdp_context_free;
    freerdp_context_new(rdp_inst);

    /* Set settings */
    settings = rdp_inst->settings;

    /* Console */
    settings->console_session = (strcmp(argv[IDX_CONSOLE], "true") == 0);
    settings->console_audio   = (strcmp(argv[IDX_CONSOLE_AUDIO], "true") == 0);

    /* --no-auth */
    settings->authentication = false;

    /* --sec rdp */
    settings->rdp_security = true;
    settings->tls_security = false;
    settings->nla_security = false;
    settings->encryption = true;
    settings->encryption_method = ENCRYPTION_METHOD_40BIT | ENCRYPTION_METHOD_128BIT | ENCRYPTION_METHOD_FIPS;
    settings->encryption_level = ENCRYPTION_LEVEL_CLIENT_COMPATIBLE;

    /* Use optimal width unless overridden */
    settings->width = client->info.optimal_width;
    if (argv[IDX_WIDTH][0] != '\0')
        settings->width = atoi(argv[IDX_WIDTH]);

    /* Use default width if given width is invalid. */
    if (settings->width <= 0) {
        settings->width = RDP_DEFAULT_WIDTH;
        guac_client_log_error(client,
                              "Invalid width: \"%s\". Using default of %i.",
                              argv[IDX_WIDTH], settings->width);
    }

    /* Round width up to nearest multiple of 4 */
    settings->width = (settings->width + 3) & ~0x3;

    /* Use optimal height unless overridden */
    settings->height = client->info.optimal_height;
    if (argv[IDX_HEIGHT][0] != '\0')
        settings->height = atoi(argv[IDX_HEIGHT]);

    /* Use default height if given height is invalid. */
    if (settings->height <= 0) {
        settings->height = RDP_DEFAULT_HEIGHT;
        guac_client_log_error(client,
                              "Invalid height: \"%s\". Using default of %i.",
                              argv[IDX_WIDTH], settings->height);
    }

    /* Set hostname */
    settings->hostname = strdup(hostname);
    settings->port = port;
    settings->window_title = strdup(hostname);

    /* Domain */
    if (argv[IDX_DOMAIN][0] != '\0')
        settings->domain = strdup(argv[IDX_DOMAIN]);

    /* Username */
    if (argv[IDX_USERNAME][0] != '\0')
        settings->username = strdup(argv[IDX_USERNAME]);

    /* Password */
    if (argv[IDX_PASSWORD][0] != '\0') {
        settings->password = strdup(argv[IDX_PASSWORD]);
        settings->autologon = 1;
    }

    /* Initial program */
    if (argv[IDX_INITIAL_PROGRAM][0] != '\0')
        settings->shell = strdup(argv[IDX_INITIAL_PROGRAM]);

    /* Session color depth */
    settings->color_depth = RDP_DEFAULT_DEPTH;
    if (argv[IDX_COLOR_DEPTH][0] != '\0')
        settings->color_depth = atoi(argv[IDX_COLOR_DEPTH]);

    /* Use default depth if given depth is invalid. */
    if (settings->color_depth == 0) {
        settings->color_depth = RDP_DEFAULT_DEPTH;
        guac_client_log_error(client,
                              "Invalid color-depth: \"%s\". Using default of %i.",
                              argv[IDX_WIDTH], settings->color_depth);
    }

    /* Audio enable/disable */
    guac_client_data->audio_enabled =
        (strcmp(argv[IDX_DISABLE_AUDIO], "true") != 0);

    /* Printing enable/disable */
    guac_client_data->printing_enabled =
        (strcmp(argv[IDX_ENABLE_PRINTING], "true") == 0);

    /* Order support */
    bitmap_cache = settings->bitmap_cache;
    settings->os_major_type = OSMAJORTYPE_UNSPECIFIED;
    settings->os_minor_type = OSMINORTYPE_UNSPECIFIED;
    settings->order_support[NEG_DSTBLT_INDEX] = true;
    settings->order_support[NEG_PATBLT_INDEX] = false; /* PATBLT not yet supported */
    settings->order_support[NEG_SCRBLT_INDEX] = true;
    settings->order_support[NEG_OPAQUE_RECT_INDEX] = true;
    settings->order_support[NEG_DRAWNINEGRID_INDEX] = false;
    settings->order_support[NEG_MULTIDSTBLT_INDEX] = false;
    settings->order_support[NEG_MULTIPATBLT_INDEX] = false;
    settings->order_support[NEG_MULTISCRBLT_INDEX] = false;
    settings->order_support[NEG_MULTIOPAQUERECT_INDEX] = false;
    settings->order_support[NEG_MULTI_DRAWNINEGRID_INDEX] = false;
    settings->order_support[NEG_LINETO_INDEX] = false;
    settings->order_support[NEG_POLYLINE_INDEX] = false;
    settings->order_support[NEG_MEMBLT_INDEX] = bitmap_cache;
    settings->order_support[NEG_MEM3BLT_INDEX] = false;
    settings->order_support[NEG_MEMBLT_V2_INDEX] = bitmap_cache;
    settings->order_support[NEG_MEM3BLT_V2_INDEX] = false;
    settings->order_support[NEG_SAVEBITMAP_INDEX] = false;
    settings->order_support[NEG_GLYPH_INDEX_INDEX] = true;
    settings->order_support[NEG_FAST_INDEX_INDEX] = true;
    settings->order_support[NEG_FAST_GLYPH_INDEX] = true;
    settings->order_support[NEG_POLYGON_SC_INDEX] = false;
    settings->order_support[NEG_POLYGON_CB_INDEX] = false;
    settings->order_support[NEG_ELLIPSE_SC_INDEX] = false;
    settings->order_support[NEG_ELLIPSE_CB_INDEX] = false;

    /* Store client data */
    guac_client_data->rdp_inst = rdp_inst;
    guac_client_data->bounded = false;
    guac_client_data->mouse_button_mask = 0;
    guac_client_data->current_surface = GUAC_DEFAULT_LAYER;
    guac_client_data->clipboard = NULL;
    guac_client_data->audio = NULL;

    /* Main socket needs to be threadsafe */
    guac_socket_require_threadsafe(client->socket);

    /* Recursive attribute for locks */
    pthread_mutexattr_init(&(guac_client_data->attributes));
    pthread_mutexattr_settype(&(guac_client_data->attributes),
                              PTHREAD_MUTEX_RECURSIVE);

    /* Init RDP lock */
    pthread_mutex_init(&(guac_client_data->rdp_lock),
                       &(guac_client_data->attributes));

    /* Clear keysym state mapping and keymap */
    memset(guac_client_data->keysym_state, 0,
           sizeof(guac_rdp_keysym_state_map));

    memset(guac_client_data->keymap, 0,
           sizeof(guac_rdp_static_keymap));

    client->data = guac_client_data;
    ((rdp_freerdp_context*) rdp_inst->context)->client = client;

    /* Pick keymap based on argument */
    if (argv[IDX_SERVER_LAYOUT][0] != '\0') {

        /* US English Qwerty */
        if (strcmp("en-us-qwerty", argv[IDX_SERVER_LAYOUT]) == 0)
            chosen_keymap = &guac_rdp_keymap_en_us;

        /* German Qwertz */
        else if (strcmp("de-de-qwertz", argv[IDX_SERVER_LAYOUT]) == 0)
            chosen_keymap = &guac_rdp_keymap_de_de;

        /* French Azerty */
        else if (strcmp("fr-fr-azerty", argv[IDX_SERVER_LAYOUT]) == 0)
            chosen_keymap = &guac_rdp_keymap_fr_fr;

        /* Failsafe (Unicode) keymap */
        else if (strcmp("failsafe", argv[IDX_SERVER_LAYOUT]) == 0)
            chosen_keymap = &guac_rdp_keymap_failsafe;

        /* If keymap unknown, resort to failsafe */
        else {

            guac_client_log_error(client,
                                  "Unknown layout \"%s\". Using the failsafe layout instead.",
                                  argv[IDX_SERVER_LAYOUT]);

            chosen_keymap = &guac_rdp_keymap_failsafe;

        }

    }

    /* If no keymap requested, assume US */
    else
        chosen_keymap = &guac_rdp_keymap_en_us;

    /* Load keymap into client */
    __guac_rdp_client_load_keymap(client, chosen_keymap);

    /* Set server-side keymap */
    settings->kbd_layout = chosen_keymap->freerdp_keyboard_layout;

    /* Connect to RDP server */
    if (!freerdp_connect(rdp_inst)) {

        guac_protocol_send_error(client->socket,
                                 "Error connecting to RDP server");
        guac_socket_flush(client->socket);

        guac_error = GUAC_STATUS_BAD_STATE;
        guac_error_message = "Error connecting to RDP server";

        return 1;
    }

    /* Send connection name */
    guac_protocol_send_name(client->socket, settings->window_title);

    /* Send size */
    guac_protocol_send_size(client->socket, GUAC_DEFAULT_LAYER,
                            settings->width, settings->height);

    /* Create glyph surfaces */
    guac_client_data->opaque_glyph_surface = cairo_image_surface_create(
                CAIRO_FORMAT_RGB24, settings->width, settings->height);

    guac_client_data->trans_glyph_surface = cairo_image_surface_create(
            CAIRO_FORMAT_ARGB32, settings->width, settings->height);

    /* Set default pointer */
    guac_rdp_set_default_pointer(client);

    /* Success */
    return 0;

}
Example #30
0
File: 5-1.c Project: Nan619/ltp-ddt
/********* main ********/
int main(int argc, char *argv[])
{
	int ret, i, j;
	pthread_t th;
	pthread_mutexattr_t ma[4], *pma[5];
	pma[4] = NULL;

	output_init();

	/* Initialize the mutex attributes */
	for (i = 0; i < 4; i++) {
		pma[i] = &ma[i];
		if ((ret = pthread_mutexattr_init(pma[i]))) {
			UNRESOLVED(ret, "pthread_mutexattr_init");
		}
	}
#ifndef WITHOUT_XOPEN
	if ((ret = pthread_mutexattr_settype(pma[0], PTHREAD_MUTEX_NORMAL))) {
		UNRESOLVED(ret, "pthread_mutexattr_settype (normal)");
	}
	if ((ret = pthread_mutexattr_settype(pma[1], PTHREAD_MUTEX_ERRORCHECK))) {
		UNRESOLVED(ret, "pthread_mutexattr_settype (errorcheck)");
	}
	if ((ret = pthread_mutexattr_settype(pma[2], PTHREAD_MUTEX_RECURSIVE))) {
		UNRESOLVED(ret, "pthread_mutexattr_settype (recursive)");
	}
	if ((ret = pthread_mutexattr_settype(pma[3], PTHREAD_MUTEX_DEFAULT))) {
		UNRESOLVED(ret, "pthread_mutexattr_settype (default)");
	}
#if VERBOSE >1
	output
	    ("Mutex attributes NORMAL,ERRORCHECK,RECURSIVE,DEFAULT initialized\n");
#endif
#else
#if VERBOSE > 0
	output
	    ("Mutex attributes NORMAL,ERRORCHECK,RECURSIVE,DEFAULT unavailable\n");
#endif
#endif

	/* Initialize the 5 mutex */
	for (i = 0; i < 5; i++) {
		if ((ret = pthread_mutex_init(&mtx[i], pma[i]))) {
		UNRESOLVED(ret, "pthread_mutex_init failed")}
		if ((ret = pthread_mutex_lock(&mtx[i]))) {
		UNRESOLVED(ret, "Initial pthread_mutex_lock failed")}
	}

#if VERBOSE >1
	output("Mutex objects are initialized\n");
#endif

	/* We don't need the mutex attribute objects anymore */
	for (i = 0; i < 4; i++) {
		if ((ret = pthread_mutexattr_destroy(pma[i]))) {
			UNRESOLVED(ret, "pthread_mutexattr_destroy");
		}
	}

	/* Initialize the semaphores */
	if (sem_init(&semsig, 0, 1)) {
		UNRESOLVED(errno, "Sem init (1) failed");
	}
	if (sem_init(&semstart, 0, 0)) {
		UNRESOLVED(errno, "Sem init (0) failed");
	}
#if VERBOSE >1
	output("Going to create the child thread\n");
#endif
	/* Start the child */
	if ((ret = pthread_create(&th, NULL, threaded, NULL))) {
		UNRESOLVED(ret, "Unable to create the thread");
	}
#if VERBOSE >1
	output("Child created\n");
#endif

	/* Monitor the child */
	for (i = 0; i < 5; i++) {	/* We will do this for the 5 kinds of mutex */
		if (sem_wait(&semstart)) {	/* Wait for the thread to be ready */
			UNRESOLVED(errno, "Unable to wait for the child");
		}
#if VERBOSE >1
		output("Child is ready for iteration %i\n", i + 1);
#endif

		ctrl = 0;	/* init the ctrl var */

		/* Send some signals to the thread */
		for (j = 0; j < 10; j++) {
			if ((ret = sem_wait(&semsig))) {
				UNRESOLVED(errno,
					   "Sem_wait failed from the signal handler");
			}

			sched_yield();	/* Let the child do its stuff - might be a nanosleep here */

			if ((ret = pthread_kill(th, SIGUSR1))) {
				UNRESOLVED(ret, "Pthread_kill failed");
			}
		}
#if VERBOSE >1
		output("Child was killed 10 times\n");
#endif

		/* Now check the thread is still waiting for the mutex */
		if (ctrl != 0) {
			FAILED
			    ("Killed child passed the pthread_mutex_lock without owning it");
		}
#if VERBOSE >1
		output("Control was OK\n");
#endif

		/* Unlock the mutex so the thread can proceed to the next one */
		if ((ret = pthread_mutex_unlock(&mtx[i]))) {
			UNRESOLVED(ret, "Mutex unlock in main failed");
		}
	}

#if VERBOSE >1
	output
	    ("The test has passed, we are now going to clean up everything.\n");
#endif

	/* Clean everything: the test has passed */
	if ((ret = pthread_join(th, NULL))) {
		UNRESOLVED(ret, "Unable to join the child");
	}

	for (i = 0; i < 5; i++) {
		if ((ret = pthread_mutex_destroy(&mtx[i]))) {
			UNRESOLVED(ret, "Unable to finally destroy a mutex");
		}
	}

	if (sem_destroy(&semstart)) {
		UNRESOLVED(errno, "Unable to destroy semstart semaphore");
	}

	if (sem_destroy(&semsig)) {
		UNRESOLVED(errno, "Unable to destroy semsig semaphore");
	}

	PASSED;
}